Number of Islands
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.
Example 1:
11110110101100000000Answer: 1
Example 2:
11000110000010000011Answer: 3
解析:最熟悉的bfs,使用队列实现
代码:
class Solution { public: int numIslands(vector<vector<char>>& grid) { if (grid.empty()) return 0; int ans=0; int dx[4]={0,1,0,-1}; int dy[4]={-1,0,1,0}; int rows=grid.size(); int cols=grid[0].size(); vector<vector<int>>vis(rows,vector<int>(cols,0)); for (int i=0; i<rows; i++) { for (int j=0; j<cols; j++) { if (vis[i][j]||grid[i][j]=='0') continue; queue<pair<int,int>>que; que.push(make_pair(i,j)); ans++; while(!que.empty()) { int posy=que.front().first; int posx=que.front().second; que.pop(); int tempy; int tempx; for (int k=0; k<4; k++) { tempy=posy+dy[k]; tempx=posx+dx[k]; if (tempy<0||tempy>=rows||tempx<0||tempx>=cols) continue; if (vis[tempy][tempx]||grid[tempy][tempx]=='0') continue; vis[tempy][tempx]=1; que.push(make_pair(tempy,tempx)); } } } } return ans; } };