1. 程式人生 > 其它 >leetcode 200 島嶼數量

leetcode 200 島嶼數量

深度優先搜尋的想法,針對一個無向圖,對這一圖進行遍歷,遇到一個‘1’就進行深度優先搜尋,遇到的‘1’都變成‘0’,代表這一個島嶼已經被記錄。島嶼的數量就是進行搜尋的次數,貼程式碼

class Solution {
private:
    void dfs(vector<vector<char>>& grid,int x,int y)
    {
        int m = grid.size();
        int n = grid[0].size();
        grid[x][y] = '0';
        if(x-1>=0 && grid[x-1
][y] == '1') dfs(grid,x-1,y); if(x+1<m && grid[x+1][y] == '1') dfs(grid,x+1,y); if(y-1>=0 && grid[x][y-1] == '1') dfs(grid,x,y-1); if(y+1<n && grid[x][y+1] == '1') dfs(grid,x,y+1); } public: int numIslands(vector<vector<char>>& grid) {
int m = grid.size(); if(!m) return 0; int n = grid[0].size(); int num = 0; for(int i = 0 ; i < m ; i++) { for(int j = 0 ; j < n ; j++) { if(grid[i][j] == '1') { num++; dfs(grid,i,j); } } }
return num; } };

廣度優先搜尋,單次搜尋中,通過佇列才儲存所有周邊的‘1’,每搜尋到一個‘1’,就將其存入佇列中,繼續進行搜尋,直到佇列中元素清空。

 1 class Solution {
 2 public:
 3     int numIslands(vector<vector<char>>& grid) 
 4     {
 5         int m = grid.size();
 6         int n = grid[0].size();
 7         int nums = 0;
 8         for(int i = 0 ; i < m ; i++)
 9         {
10             for(int j = 0 ; j < n ; j++)
11             {
12                 if(grid[i][j] == '1')
13                 {
14                     nums++;
15                     grid[i][j] = '0';
16                     queue<pair<int,int>> neibor;
17                     neibor.push({i,j});
18                     while(!neibor.empty())
19                     {
20                         auto temp = neibor.front();
21                         neibor.pop();
22                         int x = temp.first;
23                         int y = temp.second;
24                         if(x-1>=0 && grid[x-1][y] == '1')
25                         {
26                             neibor.push({x-1,y});
27                             grid[x-1][y] = '0';
28                         }
29                         if(x+1<m && grid[x+1][y] == '1')
30                         {
31                             neibor.push({x+1,y});
32                             grid[x+1][y] = '0';
33                         }
34                         if(y-1>=0 && grid[x][y-1] == '1')
35                         {
36                             neibor.push({x,y-1});
37                             grid[x][y-1] = '0';
38                         }
39                         if(y+1<n && grid[x][y+1] == '1')
40                         {
41                             neibor.push({x,y+1});
42                             grid[x][y+1] = '0';
43                         }
44                     } 
45                 }
46             }
47         } 
48         return nums; 
49     }
50 };