Problem
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'
.
Solution
The idea to solve this problem is to use DFS or BFS to visit adjacent lands for each unvisited land. When the adjacent cell is land, continue to visit its adjacent lands until it can no longer expand. In this way, an island is obtained. Then, find the next unvisited land and do the same action above until all the lands have been visited.
DFS
- Time:
- Space:
class Solution { public int numIslands(char[][] grid) { boolean[][] visited = new boolean[grid.length][grid[0].length]; int islands = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == '1' && !visited[i][j]) { dfs(grid, i, j, visited); islands++; } } } return islands; } private void dfs(char[][] grid, int i, int j, boolean[][] visited) { visited[i][j] = true; int[][] dirs = new int[][] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; for (int[] dir : dirs) { int r = i + dir[0]; int c = j + dir[1]; if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) continue; if (visited[r][c] || grid[r][c] == '0') continue; dfs(grid, r, c, visited); } } }
BFS
- Time:
- Space:
class Solution { public int numIslands(char[][] grid) { boolean[][] visited = new boolean[grid.length][grid[0].length]; int islands = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == '1' && !visited[i][j]) { bfs(grid, i, j, visited); islands++; } } } return islands; } private void bfs(char[][] grid, int row, int col, boolean[][] visited) { Queue<int[]> queue = new ArrayDeque<>(); queue.offer(new int[] {row, col}); int[][] dirs = new int[][] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; while (!queue.isEmpty()) { int[] pos = queue.poll(); if (visited[pos[0]][pos[1]]) continue; visited[pos[0]][pos[1]] = true; for (int[] dir : dirs) { int r = pos[0] + dir[0]; int c = pos[1] + dir[1]; if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) continue; if (grid[r][c] == '0' || visited[r][c]) continue; queue.offer(new int[] {r, c}); } } } }
Reference
- 200. Number of Islands, LeetCode.
- 200. Number of Islands, LeetCode Solutions.