Topic Connection
https://leetcode.com/problems/number-of-islands/
Number of Islandsdescription
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 are formed by connecting adjacent lands horizontally or vertically. Assume all four edges of the grid is all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer:1
Example 2:
11000
11000
00100
00011
Answer:3
const int dx[] = {0, 0, 0,-1, 1}, dy[] = {0,-1, 1, 0, 0};class solution {public:int numislands (vector<vector<c har>>& grid) {if (Grid.empty () | | grid[0].empty ()) return 0;ans = 0, n = grid.size (), M = Grid[0].size (); for (in t i = 0; I < n; i++) {for (int j = 0; J < m; J + +) {if (grid[i][j] = = ' 1 ') {DFS (grid, I, j); ans++;}}} return ans;} void Dfs (vector<vector<char>>& grid, int x, int y) {for (int i = 0; i < 5; i++) {int NX = Dx[i] + x, NY = Dy[i] + y;if (NX < 0 | | NX >= N | | NY < 0 | | ny >= m) continue;if (grid[nx][ny] = = ' 1 ') {grid[x][y] = ' 0 ';d FS (Grid, NX, NY);}}} Private:int ans, N, M;};
Leetcode Number of Islands