島嶼個數——深度優先搜索

這是leetcode 上的一道算法題目,鏈接:島嶼個數

給你一個由 ‘1’(陸地)和 ‘0’(水)組成的的二維網格,請你計算網格中島嶼的數量。

島嶼總是被水包圍,並且每座島嶼只能由水平方向和/或豎直方向上相鄰的陸地連接形成。
此外,你可以假設該網格的四條邊均被水包圍。

例子如下

示例 1:

輸入:
11110
11010
11000
00000
輸出: 1
解釋:本例中的1彼此相連,即認爲只有一塊陸地
--------------------------------------------
示例 2:
輸入:
11000
11000
00100
00011
輸出: 3
解釋: 每座島嶼只能由水平和/或豎直方向上相鄰的陸地連接而成。

廣度優先搜索算法 遍歷每遇到 1,就把它以及周圍相連的1變爲0,然後接着遍歷

class Solution {
    public int numIslands(char[][] grid) {
        if(null == grid || grid.length == 0) return 0;
        int row =  grid.length;
        int col = grid[0].length;
        int result = 0;
        int[] xx = new int[]{0,0,1,-1};
        int[] yy = new int[]{1,-1,0,0};
        Queue<Integer> list = new LinkedList<>();
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                if(grid[i][j] == '1'){
                    result++;
                    grid[i][j] = '0';
                    list.add(i*col + j);
                }               
                while(list.size() > 0){                    
                    int temp = list.remove();
                    for(int k = 0; k < 4; k++){ // 上下左右四個方向的1都改成0
                        int x = temp/col + xx[k];
                        int y = temp%col + yy[k];
                        if(x >= 0 && y >=0 && x < row && y < col && grid[x][y] == '1'){
                            grid[x][y] = '0';
                            list.add(x*col + y);
                        }
                    }

                }
            }
        }
        return result;
    }
}

嘗試優先算法實現 用遞歸或回溯的方式來實現

class Solution {
    void dfs(char[][] grid, int r, int c) {
        int nr = grid.length;
        int nc = grid[0].length;

        if (r < 0 || c < 0 || r >= nr || c >= nc || grid[r][c] == '0') {
            return;
        }

        grid[r][c] = '0';
        dfs(grid, r - 1, c);
        dfs(grid, r + 1, c);
        dfs(grid, r, c - 1);
        dfs(grid, r, c + 1);
    }

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

        int nr = grid.length;
        int nc = grid[0].length;
        int num_islands = 0;
        for (int r = 0; r < nr; ++r) {
            for (int c = 0; c < nc; ++c) {
                if (grid[r][c] == '1') {
                    ++num_islands;
                    dfs(grid, r, c);
                }
            }
        }
        return num_islands;
    }
}

關於深度優先算法和廣度優先算法,可以參考這篇文章–>算法詳解

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章