[LeetCode] 200. Number of Islands 岛屿的数量

     这道求岛屿数量的题的本质是求矩阵中连续区域的个数,很容易想到需要用深度优先搜索 DFS 来解,我们需要建立一个 visited 数组用来记录某个位置是否被访问过。由于本题没有要求不能破坏原矩阵,

所以可以使用DFS的方法将矩阵中每一块连续的1都置为0,以此标记以访问过,则可以到空间复用的目的。特别重要的,在访问数组的时候一定要注意验证下标的大小,防止访问下标越界;和本题还可以使用

BFS和并查集的方法,此处暂不讨论。

 1 /*
 2  * @Descripttion: 
 3  * @version: 
 4  * @Author: wangxf
 5  * @Date: 2020-04-12 16:38:48
 6  * @LastEditors: Do not edit
 7  * @LastEditTime: 2020-04-12 21:59:09
 8  */
 9 /*
10  * @lc app=leetcode.cn id=200 lang=cpp
11  *
12  * [200] 岛屿数量
13  */
14 
15 // @lc code=start
16 #include<bits/stdc++.h>
17 using namespace std;
18 class Solution {
19 public:
20     int numIslands(vector<vector<char>>& grid) {
21           int res = 0;
22           if ((!grid.empty())&&grid.size()>0)//给定矩阵非空
23           {
24             for (int i = 0; i < grid.size(); i++)
25                 for (int j = 0; j < grid[0].size(); j++)
26                 {
27                     if (grid[i][j] == '1')//遍历到岛屿
28                     {
29                         ++res;
30                         dfs(grid,i,j);
31                     }   
32                 } 
33           }
34           return res;
35     }
36     
37     void dfs(vector<vector<char>>& grid,int i,int j)
38     { 
39         if(!(i>=0&&i<grid.size()&&j>=0&&j<grid[0].size()))
40         {
41             return;
42         }
43         if(grid[i][j] == '0') return ;
44         grid[i][j] = '0';//标记访问过,复用标记数组
45       
46         int step_row[4]={0,0,-1,1};
47         int step_col[4]={-1,1,0,0};
48         for(int k=0;k<4;++k)
49         {
50            dfs(grid,i+step_row[k],j+step_col[k]);
51         }
52         return; 
53     }
54 };
55 // @lc code=end

 

posted @ 2020-04-12 22:10  谁在写西加加  阅读(180)  评论(0编辑  收藏  举报