【廣度優先遍歷】Number of Islands
阿新 • • 發佈:2019-02-14
題目:leetcode
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:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
分析:
用廣度優先遍歷,先把矩形外圍四條邊的1變成0,然後把矩形內部的1變成0。每一次需要改變值,島嶼的數量就加1.
class Solution { public: int numIslands(vector<vector<char>> &grid) { if(grid.empty() || grid[0].empty()) return 0; int count=0; int rows=grid.size(),cols=grid[0].size(); for(int j=0;j<cols;j++) { if(grid[0][j]=='1') { count++; numIslands_core(grid,0,j); } if(grid[rows-1][j]=='1') { count++; numIslands_core(grid,rows-1,j); } } for(int i=1;i<rows-1;i++) { if(grid[i][0]=='1') { count++; numIslands_core(grid,i,0); } if(grid[i][cols-1]=='1') { count++; numIslands_core(grid,i,cols-1); } } for(int i=1;i<rows-1;i++) { for(int j=1;j<cols-1;j++) { if(grid[i][j]=='1') { count++; numIslands_core(grid,i,j); } } } return count; } void numIslands_core(vector<vector<char>> &grid,int i,int j) { if(grid[i][j]=='0') return; else grid[i][j]='0'; if(i>0) numIslands_core(grid,i-1,j); if(i<grid.size()-1) numIslands_core(grid,i+1,j); if(j>0) numIslands_core(grid,i,j-1); if(j<grid[0].size()-1) numIslands_core(grid,i,j+1); } };