Given a 2d grid map of
'1'
s (land) and '0'
s (water), count 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: 11110 11010 11000 00000 Output: 1
Example 2:
Input: 11000 11000 00100 00011 Output: 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int numIslands(char[][] grid) { | |
// corner cases | |
if (grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0) { | |
return 0; | |
} | |
// main logic - 2 for loops and using every non visited land as entry point to call dfs | |
int counter = 0; | |
m = grid.length; | |
n = grid[0].length; | |
visited = new boolean[m][n]; | |
for (int i = 0; i < m; i++) { | |
for (int j = 0; j < n; j++) { | |
if ( !visited[i][j] && (grid[i][j] == '1')) { | |
dfs(grid, i, j); | |
counter++; | |
} | |
} | |
} | |
return counter; | |
} | |
private int m = 0; | |
private int n = 0; | |
private boolean[][] visited = null; | |
private int[] dx = new int[]{0, 0, 1, -1}; | |
private int[] dy = new int[]{1, -1, 0, 0,}; | |
private void dfs(char[][] grid, int i , int j) { | |
// corner cases | |
if (visited[i][j] || grid[i][j] == '0') { | |
return; | |
} | |
visited[i][j] = true; | |
for (int t = 0; t < 4; t++) { | |
int x = dx[t] + i; | |
int y = dy[t] + j; | |
if (isValid(x, y) && !visited[x][y] && (grid[x][y] == '1')) { | |
dfs(grid, x, y); | |
} | |
} | |
} | |
private boolean isValid(int x, int y) { | |
return x >= 0 && x < m && y >= 0 && y < n; | |
} | |
} |
No comments:
Post a Comment