Leetcode每日两题程序员

Leetcode 200. Number of Islands

2017-11-19  本文已影响10人  ShutLove

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.

思路:碰见是1的点就进行宽度搜索,并把它的所有邻岛标记为0,总岛数+1.

public int numIslands(char[][] grid) {
    if (grid == null || grid.length == 0 || grid[0].length == 0) {
        return 0;
    }

    int res = 0;
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[0].length; j++) {
            if (grid[i][j] == '1') {
                bfs(grid, i, j);
                res++;
            }
        }
    }

    return res;
}

private void bfs(char[][] grid, int i, int j) {
    int[] dx = {0, 1, 0, -1};
    int[] dy = {1, 0, -1, 0};
    Queue<int[]> q = new LinkedList<>();
    int[] coor = {i, j};
    q.offer(coor);
    while (!q.isEmpty()) {
        int[] cur = q.poll();
        grid[cur[0]][cur[1]] = '0';
        for (int k = 0; k < 4; k++) {
            int tx = cur[0] + dx[k];
            int ty = cur[1] + dy[k];
            if (tx < 0 || tx >= grid.length || ty < 0 || ty >= grid[0].length || grid[tx][ty] == '0') {
                continue;
            }
            int[] neighbor = {tx, ty};
            q.offer(neighbor);
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读