Leetcode 200. Number of Islands

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);
        }
    }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Number of Islands Given a 2d grid map of '1's (land) and ...
    gammaliu閱讀 400評論 0 0
  • Problem Given a 2d grid map of '1's (land) and '0's (wate...
    Branch閱讀 778評論 0 1
  • 分析 只需要對每一個陸地區域做一次dfs,每次dfs中將已經遍歷的陸地網格“1”變為水域網格“0”(防止再次遍歷導...
    胡哈哈哈閱讀 376評論 0 0
  • 原題 給一個01矩陣,求不同的島嶼的個數。0代表海,1代表島,如果兩個1相鄰,那么這兩個1屬于同一個島。我們只考慮...
    Jason_Yuan閱讀 720評論 0 0
  • 今天看了鳳紅邪的文章,覺得太對了。 讓我想起來,從小大家就是總是說我這里好那里好,或者說別人家的孩子怎么好。結果我...
    Yoscool閱讀 719評論 6 4