Algorithms and Data Structures/Coding Practices

LeetCode 200. Number of Islands

brightlightkim 2022. 7. 16. 11:37

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return 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:

Input: grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
Output: 1

Example 2:

Input: grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
Output: 3

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is '0' or '1'.
class Solution {
    public int numIslands(char[][] grid) {
        // c: column, r: row
        int islandNum = 0;
        int m = grid.length;
        int n = grid[0].length;
        for (int c = 0; c < m; c++){
            for (int r = 0; r < n; r++){
                if (grid[c][r] == '1'){
                    islandNum += 1;
                    DFSMarking(grid, c, r, m, n);
                }
            }
        }
        return islandNum;
    }
    
    private void DFSMarking(char[][] grid, int i, int j, int m, int n) {
        if (i < 0 || j < 0 || i >= m || j >= n) return;
        if (grid[i][j] != '1') return;
        grid[i][j] = '0';
        DFSMarking(grid, i + 1, j, m, n);
        DFSMarking(grid, i - 1, j, m, n);
        DFSMarking(grid, i, j + 1, m, n);
        DFSMarking(grid, i, j - 1, m, n);
    }
}