1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| void dfs(vector<vector<char>>& grid, int x, int y) { int next[4][2] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} }; grid[x][y] = '0'; for(int i = 0; i < 4; i++) { int nx = x + next[i][0]; int ny = y + next[i][1]; if(nx >= 0 && nx < grid.size() && ny >= 0 && ny < grid[0].size() && grid[nx][ny] == '1') dfs(grid, nx, ny); }
}
int numIslands(vector<vector<char>>& grid) { if(grid.empty() || grid[0].empty()) return 0; int res = 0; int m = grid.size(), n = grid[0].size(); for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) if(grid[i][j] == '1') { res++; dfs(grid, i, j); }
return res; }
|