[#B] 200 Number of Islands - LeetCode
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.
Input: 11110 11010 11000 00000 Output: 1
Input: 11000 11000 00100 00011 Output: 3
通过深度遍历,把每个 ‘1’ 周围的 ‘1’ 都置为 ‘0’ 。
class Solution {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0)
return 0;
int numOfIslands = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
numOfIslands++;
dfs(grid, i, j);
}
}
}
return numOfIslands;
}
public void dfs(char[][] grid, int r, int c) {
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length)
return;
if (grid[r][c] == '1'){
grid[r][c] = '0';
dfs(grid, r - 1, c);
dfs(grid, r, c + 1);
dfs(grid, r + 1, c);
dfs(grid, r, c - 1);
}
}
}class Solution {
public:
int d[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int m,n;
int numIslands(vector<vector<char>>& grid) {
m = grid.size();
if (m == 0)
return 0;
n = grid[0].size();
if (n == 0)
return 0;
int islands = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
islands++;
dfs(grid, i, j);
}
}
}
return islands;
}
void dfs(vector<vector<char>>& grid, int x, int y) {
if (grid[x][y] == '1') {
grid[x][y] = '0';
for (int i = 0; i < 4; i++) {
int newX = x + d[i][0];
int newY = y + d[i][1];
if (inArea(newX, newY) && grid[newX][newY] == '1') {
dfs(grid, newX, newY);
}
}
}
}
bool inArea(int x, int y) {
return x >= 0 && x < m && y >= 0 && y < n;
}
};