200. Number of Islands(广度优先/深度优先的经典问题)
来源:互联网 发布:邯郸煤炭软件 编辑:程序博客网 时间:2024/06/05 03:46
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 } } }};
阅读全文
0 0
- 200. Number of Islands(广度优先/深度优先的经典问题)
- 【广度优先遍历】Number of Islands
- leetcode 200. Number of Islands DFS深度优先遍历
- 关于深度优先和广度优先的问题
- 走迷宫问题(深度优先遍历 + 广度优先遍历)
- 图的深度(广度)优先搜索
- 图的广度优先,深度优先(邻接矩阵)
- (1.2.6.1)图的遍历--深度优先、广度优先
- 图的遍历 (深度优先 广度优先)
- 深度优先,广度优先的学习(待续)
- Graph(3)--图的遍历(深度优先&广度优先)
- 图的深度优先,广度优先
- 数的广度优先和深度优先
- 图的遍历-(深度优先&广度优先)
- 深度优先和广度优先的理解
- 图的深度优先和广度优先
- 图的遍历:深度优先、广度优先
- 迷宫问题的算法(优于递归、深度优先、广度优先)
- jquery_selector02
- 基类-BaseActivity
- UVA 11375 Matches (dp+高精度)【模板】
- Jedis 读取配置文件
- sql注入
- 200. Number of Islands(广度优先/深度优先的经典问题)
- Problem D. Ice Cream Tower (The 2016 ACM-ICPC Asia China-Final Contest)(二分)
- python -day07
- VS包含目录、附加依赖项、库目录设置
- JZOJ 5329. 【NOIP2017提高A组模拟8.22】时间机器
- POJ
- NDK下 将Platinum SDK 编译成so库 (android
- HDU 6166 Senior Pan
- Linux下信号详解