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);
}
}
'Algorithms and Data Structures > Coding Practices' 카테고리의 다른 글
LeetCode 1029. Two City Scheduling (0) | 2022.07.17 |
---|---|
LeetCode 3. Longest Substring Without Repeating Characters (0) | 2022.07.16 |
AlgoExpert InsertionSort (0) | 2022.07.16 |
AlgoExpert Bubble Sort (0) | 2022.07.16 |
AlgoExpert Find Three Largest Numbers (0) | 2022.07.15 |