本文记录的是刷题过程中的重要概念和笔记。如有侵权,请联系删除。
原题
面试题 16.19. 水域大小
https://leetcode.cn/problems/pond-sizes-lcci/
你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。
母题&方法
图的遍历算法:DFS BFS
思路
BFS
昨天的思路
class Solution{
private:
// const int dirs[8][2]={
// {0,1}, {1,0},{0,-1},{-1,0},
// {1,1},{1,-1},{-1,1},{-1,-1}
// };
// 1* : 注意写法
bool static cmp(int a,int b){
return a<b;
}
int traversal(vector<vector<int>>& land, int x, int y){
// if(land[x][y]!=0) return 0;
int res=1;
land[x][y]=1;
queue<pair<int,int>> que;
que.push(pair<int,int>(x,y));
while(!que.empty()){
pair<int,int> tmp=que.front();
que.pop();
// land[tmp.first][tmp.second]=1;
// 2*: 遍历八个方位的新的写法,注意(0,0)是否需要特殊处理
for(int i=-1;i<2;i++){
for(int j=-1;j<2;j++){
// if(i==0&&j==0) continue;
// BFS:遍历八个方位
int tmpX=tmp.first + i;
int tmpY=tmp.second + j;
if(0<=tmpX && tmpX<land.size()
&& 0<=tmpY && tmpY<land[0].size()
&& land[tmpX][tmpY]==0){
que.push(pair<int,int>(tmpX,tmpY));
res++;
// 需要先进行标记,否则会重复记录,导致值错误。
land[tmpX][tmpY]=1;
}
}
}
}
return res;
}
public:
vector<int> pondSizes(vector<vector<int>>& land) {
vector<int> res;
for(int i=0;i<land.size();i++){
for(int j=0;j<land[0].size();j++){
if(land[i][j]==0){
res.push_back(traversal(land,i,j));
}
}
}
sort(res.begin(),res.end(),cmp);
return res;
}
};
// 1* : 注意写法
bool static cmp(int a,int b){
return a<b;
}
// 2*: 遍历八个方位的新的写法,注意(0,0)是否需要特殊处理
for(int i=-1;i<2;i++){
for(int j=-1;j<2;j++){
// if(i==0&&j==0) continue;
DFS
class Solution{
private:
// const int dirs[8][2]={
// {0,1}, {1,0},{0,-1},{-1,0},
// {1,1},{1,-1},{-1,1},{-1,-1}
// };
// 1* : 注意写法
bool static cmp(int a,int b){
return a<b;
}
int dfs(vector<vector<int>>& land, int x, int y){
if(land[x][y]!=0) return 0;
int res=1;
land[x][y]=1;
for(int i=-1;i<2;i++){
for(int j=-1;j<2;j++){
if(i==0 && j==0) continue;
if(0<=x+i && x+i<land.size() && 0<=y+j
&& y+j<land[0].size() && land[x+i][y+j]==0){
res+=dfs(land,x+i,y+j);
}
}
}
return res;
}
public:
vector<int> pondSizes(vector<vector<int>>& land) {
vector<int> res;
for(int i=0;i<land.size();i++){
for(int j=0;j<land[0].size();j++){
if(land[i][j]==0){
res.push_back(dfs(land,i,j));
}
}
}
sort(res.begin(),res.end(),cmp);
return res;
}
};