【LeetCode】島嶼數量

1.題目

題目:給定一個由 ‘1’(陸地)和 ‘0’(水)組成的的二維網格,計算島嶼的數量。一個島被水包圍,並且它是通過水平方向或垂直方向上相鄰的陸地連接而成的。你可以假設網格的四個邊均被水包圍。示例 1:輸入:
11110
11010
11000
00000

輸出: 1
示例 2:輸入:
11000
11000
00100
00011

輸出: 3

2.解題思路

  • 遍歷所有的節點,利用DFS的方式將其周圍的1全部賦值爲0, 如果是0直接跳過(如果不跳過會把整個圖都賦值爲0一遍)

3.代碼實現

3.1 遞歸實現

class Solution {
    public int numIslands(char[][] grid) {
        // int row = grid.length;
        // int col = grid[0].length;   IndexOutOfBoundException
        int res = 0;
        for(int i = 0; i < grid.length; i++) {
            for(int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == '1'){
                    res++;
                    dfs(grid, i , j);
                }
            }
        }
        return res;
    }
    
    public void dfs(char[][] grid, int i, int j) {
        if (i < 0 || j < 0 || i >= grid.length || j >= grid[i].length) 
            return;
        if (grid[i][j] == '0')
            return;
        grid[i][j] = '0';
        dfs(grid, i + 1 , j);
        dfs(grid, i , j + 1);
        dfs(grid, i - 1 , j);
        dfs(grid, i , j - 1);
    }
}

3.2非遞歸實現

class Solution {
    public int numIslands(char[][] grid) {
        // int row = grid.length;
        // int col = grid[0].length;   IndexOutOfBoundException
        int res = 0;
        for(int i = 0; i < grid.length; i++) {
            for(int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == '1'){
                    res++;
                    dfs(grid, i , j);
                }
            }
        }
        return res;
    }
    
    // recursion
    // public void dfs(char[][] grid, int i, int j) {
    //     if (i < 0 || j < 0 || i >= grid.length || j >= grid[i].length) 
    //         return;
    //     if (grid[i][j] == '0')
    //         return;
    //     grid[i][j] = '0';
    //     dfs(grid, i + 1 , j);
    //     dfs(grid, i , j + 1);
    //     dfs(grid, i - 1 , j);
    //     dfs(grid, i , j - 1);
    // }
    
    //non-recursion
    
    class IndexNode {
        int i;
        int j;
        public IndexNode(int i, int j) {
            this.i = i;
            this.j = j;
        }
    }
    public void dfs(char[][] grid, int i, int j) {
        Queue<IndexNode> queue = new LinkedList<>();
        queue.add(new IndexNode(i, j));
        IndexNode temp = null;
        while(!queue.isEmpty()) {
            temp = queue.poll();
            if (temp.i < 0 || temp.j < 0 || temp.i >= grid.length || temp.j >= grid[i].length) 
                continue;
            if (grid[temp.i][temp.j] == '0')
                continue;

            grid[temp.i][temp.j] = '0';
            queue.add(new IndexNode(temp.i + 1 , temp.j));
            queue.add(new IndexNode(temp.i , temp.j + 1));
            queue.add(new IndexNode(temp.i - 1 , temp.j));
            queue.add(new IndexNode(i , temp.j - 1));
        }

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