題目描述:
給定一個由 '1'(陸地)和 '0'(水)組成的的二維網格,計算島嶼的數量。一個島被水包圍,並且它是通過水平方向或垂直方向上相鄰的陸地連接而成的。你可以假設網格的四個邊均被水包圍。
示例 1:
輸入:
11110
11010
11000
00000
輸出: 1
示例 2:
輸入:
11000
11000
00100
00011
輸出: 3
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/number-of-islands
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
這周終於做到了圖相關的算法題,這道題目應該屬於圖算法中比較基礎的,通過DFS或者BFS把‘1’附近所有的‘1’遍歷完畢就算一個島,從左上到右下完整遍歷一遍即可判斷島嶼數量,這裏回憶了一下DFS使用到的數據結構是棧,BFS使用的是隊列,兩者都可以直接使用C++STL裏的標準容器實現,而不用自己再去寫一個容器。
這裏我用的是BFS,代碼如下:
class Solution {
public:
bool inIsland(vector<vector<char>> & grid, pair<int,int>index) //判斷某一點是否越界
{
int M = grid.size();
if(!M) return false;
int N = grid[0].size();
if(index.first>=0&&index.first<M&&index.second>=0&&index.second<N) return true;
else return false;
}
int numIslands(vector<vector<char>>& grid) {
int M = grid.size();
if(!M) return 0;
int N = grid[0].size(); //行數M,列數N
int res=0;
queue<pair<int,int>> BFS; //BFS使用隊列初始化
for(int i=0;i<M;i++)
{
for(int j=0;j<N;j++) //從(0,0)開始遍歷
{
if(grid[i][j]=='0') continue; //‘0’說明是海水,直接跳過,少了這句continue有的案例會超時
if(grid[i][j]=='1')
{
BFS.push(make_pair(i,j)); //遍歷到‘1’,入隊
//grid[i][j] = 0;
res++; //島嶼數量+1
while(!BFS.empty()) //遍歷這個‘1’附近的所有‘1’作爲一個島嶼
{
pair<int,int> temp = BFS.front();
BFS.pop();
if(grid[temp.first][temp.second]=='0') continue; //這句其實應該可以省略
grid[temp.first][temp.second] = '0'; //已遍歷過的置‘0’表示已遍歷
pair<int,int> up = make_pair(temp.first-1, temp.second);
pair<int,int> down = make_pair(temp.first+1, temp.second);
pair<int,int> left = make_pair(temp.first, temp.second-1);
pair<int,int> right = make_pair(temp.first, temp.second+1);
if(inIsland(grid,up)&&grid[up.first][up.second]=='1') BFS.push(up);
if(inIsland(grid,down)&&grid[down.first][down.second]=='1') BFS.push(down);
if(inIsland(grid,left)&&grid[left.first][left.second]=='1') BFS.push(left);
if(inIsland(grid,right)&&grid[right.first][right.second]=='1') BFS.push(right); //當前訪問的點,上、下、左、右若爲‘1’則入隊,進入廣度優先遍歷,直到所有的‘1’遍歷完,這一個島嶼宣告遍歷結束
}
}
}
}
return res;
}
};
優化點:1. 上、下、左、右四個點的操作可以通過兩個數組[-1,1,0,0], [0,0,-1,1]來實現
2.並查集的方法
並查集的方法目前還沒有完全掌握,等到二刷時嘗試一下,也會嘗試寫一下DFS,通過做題來複習算法。