经典算法题之Number of Islands

来源:互联网 发布:php换行代码 编辑:程序博客网 时间:2024/06/14 17:19

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

用DFS思想

class Solution {public:int dfs(vector<vector<char> >& grid, int row, int col) {grid[row][col]='x';if(((row+1) < grid.size()) && grid[row+1][col]=='1') {//grid[row+1][col]='0';dfs(grid, row+1, col);}if(((col+1) <grid[0].size()) && grid[row][col+1]=='1') {//grid[row][col+1]='0';dfs(grid, row, col+1);}/*以下两种情况刚开始忽略掉了,当出现 100    111 101 或 010 111    111 时就会得到错误答案 */if(row-1>=0 && grid[row-1][col]=='1') {dfs(grid, row-1, col);}if(col-1>=0 && grid[row][col-1]=='1') {dfs(grid, row, col-1);}return 0;}    int numIslands(vector<vector<char> >& grid) {        if(grid.empty()||grid[0].empty())return 0;int count=0;for(int i=0; i<grid.size(); ++i) {for(int j=0; j<grid[0].size(); ++j) {if(grid[i][j]=='1') {dfs(grid, i, j);++count;}}}return count;    }}; 

0 0
原创粉丝点击