Given a 2d grid map ‘1‘
of S (land) ‘0‘
and 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
credits:
special thanks to @mithmatt for adding this problem and creating all test cases.
int R, c;int dir[4][2] = {1, 0,-1, 0, 0, 1, 0,-1};bool * * Vis;char * * g;void dfs (int pi, int pj) {VIS[PI][PJ] = True;i NT NPI, npj;for (int i = 0; i < 4; i++) {NPI = pi + dir[i][0];npj = pj + dir[i][1];if (0 <= NPI && NPI < R && 0 <= npj && npj < C &&!VIS[NPI][NPJ] && G[NPI][NPJ] = = ' 1 ') DFS (NPI, NPJ);}} int Numislands (char **grid, int numrows, int numcolumns) {G = Grid;vis = (BOOL *) malloc (sizeof (bool*) * numrows); for (int i = 0; i < numrows; i++) Vis[i] = (BOOL *) malloc (sizeof (BOOL) * numcolumns); for (int i = 0; i < numrows; i++) for (int j = 0; J < Numcolu MNs J + +) vis[i][j] = false;int ans = 0; R = NumRows; C = numcolumns;for (int i = 0; i < numrows; i++) for (int j = 0; J < NumColumns; J + +) if (!vis[i][j] && g[i][j ] = = ' 1 ') {ans++;d fs (i, j);} for (int i = 0, i < numrows; i++) free (vis[i]), free (VIS), return ans;
Leetcode OJ Number of Islands