200. Number of Islands

来源:互联网 发布:网络电视直播软件2017 编辑:程序博客网 时间:2024/06/08 01:27

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

坐标型的BFS题目,注意4个方向坐标的产生方法以及边界值的判断

class Solution {    public int numIslands(char[][] grid) {        if (grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0) {            return 0;        }        int m = grid.length;        int n = grid[0].length;        boolean[][] flag = new boolean[m][n];        int result = 0;        Queue<int[]> queue = new LinkedList<>();        for (int i = 0; i < m; i++) {            for (int j = 0; j < n; j++) {                if (grid[i][j] == '1' && !flag[i][j]) {                    flag[i][j] = true;                    result++;                    queue.offer(new int[] {i, j});                    bfs(queue, flag, grid, m, n);                }            }        }        return result;    }    private void bfs(Queue<int[]> queue, boolean[][] flag, char[][] grid, int m, int n) {        int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};        while (!queue.isEmpty()) {            int[] cell = queue.poll();            for (int[] d : dirs) {                int r = cell[0] + d[0];                int c = cell[1] + d[1];                if (r <  0 || r >= m || c < 0 || c >= n || flag[r][c] || grid[r][c] == '0') {                    continue;                }                flag[r][c] = true;                queue.add(new int[] {r, c});            }        }    }}