您的位置:首页 > 其它

200. Number of Islands(广度优先/深度优先的经典问题)

2017-08-22 19:47 225 查看
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:
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.

哈哈哈,很快就AC了,真是爽啊

解答:

class Solution {
public:
vector<vector<int>> book;//mark if a point has been visited or not,it's global
int numIslands(vector<vector<char>>& grid) {
int color=0;//use number from -1 to -n to color the graph, initially set it to be 0
int row=grid.size();
if(row==0)return 0;
int col=grid[0].size();
vector<vector<int>> init(row,vector<int>(col,0));//use it to initialize book[]
book=init;
for(int i=0;i<row;i++){//use dfs on any point of '1'
for(int j=0;j<col;j++){
if(grid[i][j]=='1'){
color--;
book[i][j]=1;//now the point has been visited, mark it
dfs(grid,i,j,color);
}
}
}
return -color;//each island needs a color, number of islands = number of colors = -color(since it starts from 0)
}
void dfs(vector<vector<char>>& grid,int x,int y,int color){
int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//different directions
int row=grid.size();
int col=grid[0].size();
grid[x][y]=color;//color the current point
for(int k=0;k<4;k++){//try 4 different directions
int tx=x+next[k][0];
int ty=y+next[k][1];
if(tx<0||tx>row-1||ty<0||ty>col-1)//the border
continue;
if(grid[tx][ty]=='1'&&book[tx][ty]==0){//if it's '1' and hasn't been visited yet
book[tx][ty]=1;//visit it
dfs(grid,tx,ty,color);//continue to search
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: