• lintcode433- Number of Islands- easy


    Given a boolean 2D matrix, 0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.

    Find the number of islands.

    Example

    Given graph:

    [
      [1, 1, 0, 0, 0],
      [0, 1, 0, 0, 1],
      [0, 0, 0, 1, 1],
      [0, 0, 0, 0, 0],
      [0, 0, 0, 0, 1]
    ]
    

    return 3.

    BFS。灌水法。BFS做的事是把当前点开始出去的连通点都变为0(和前面那题写法差不多)。main里面做的事是遍历所有点,碰到1就计数cnt++,然后调用bfs把当前块变0不影响后面的遍历。最后cnt就是答案。

    public class Solution {
        /*
         * @param grid: a boolean 2D matrix
         * @return: an integer
         */
        public int numIslands(boolean[][] grid) {
            // write your code here
            if (grid == null || grid.length == 0 || grid[0].length == 0) {
                return 0;
            }
            
            int h = grid.length;
            int w = grid[0].length;
            int cnt = 0;
            for (int x = 0; x < w; x++) {
                for (int y = 0; y < h; y++) {
                    if (grid[y][x]) {
                        cnt++;
                        bfs(grid, x, y);
                    }
                }
            }
            return cnt;
            
        }
        
        private void bfs (boolean[][] grid, int x, int y) {
            
            grid[y][x] = false;
            int[] dx = {0, -1, 0, 1};
            int[] dy = {-1, 0, 1, 0};
            int h = grid.length;
            int w = grid[0].length;
            
            for (int i = 0; i < 4; i++) {
                int cx = x + dx[i];
                int cy = y + dy[i];
                if (cx >= 0 && cx < w && cy >= 0 && cy < h && grid[cy][cx]) {
                    bfs(grid, cx, cy);
                }
            }
        }
    }
  • 相关阅读:
    MySQL高级【一】索引和视图
    SpringMVC【八】文件上传和下载
    SpringMVC【七】拦截器
    SpringMVC【六】AJAX
    python
    SqlServer优化之批量插入(SqlBulkCopy、表值参数)
    SQL中merge into用法
    Asp.Net MVC Filter权限过滤使用说明 FilterConfig类
    .NET-ORM框架EF-Code First代码优先
    asp.net mvc框架之EF的使用
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7743013.html
Copyright © 2020-2023  润新知