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
Simple DFS-seeking unicom block.
classSolution { Public: voidDfsintXinty,vector<vector<Char> >&g) {Used[x][y]=1; for(intI=0;i<4; i++){ inttx=x+Dx[i]; intty=y+Dy[i]; if(tx>=0&&tx<n&&ty>=0&&ty<m&&used[tx][ty]==0&&g[tx][ty]=='1') {DFS (TX,TY,G); } } return; } intNumislands (vector<vector<Char> >&grid) {N=grid.size (); if(n==0)return 0; M= grid[0].size (); Used= vector<vector<int> > (n,vector<int> (M,0)); intans=0; for(intI=0; i<n;i++){ for(intj=0; j<m;j++){ if(used[i][j]==0&&grid[i][j]=='1') {DFS (I,j,grid); Ans++; } } } returnans; } Private: intn,m; intdx[4]={0,0,1,-1}; intdy[4]={1,-1,0,0}; Vector<vector<int> >used;};
Leetcode 200. Number of Islands (DFS)