你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。
示例:
输入:
[
[0,2,1,0],
[0,1,0,1],
[1,1,0,1],
[0,1,0,1]
]
输出: [1,2,4]
提示:
0 < len(land) <= 1000
0 < len(land[i]) <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/pond-sizes-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
借鉴大佬的方法:
class Solution {
private:
vector<int>res;
int dir[8][2] = {{1,0},{-1,0},{0,1},{0,-1},{1,-1},{1,1},{-1,1},{-1,-1}};
int row,col;
public:
int dfs(vector<vector<int>>& land, int i,int j){
if(i<0||i>=row||j<0||j>=col||land[i][j]!=0){
return 0;
}
land[i][j]=1;
int area = 1;
for(int t=0;t<8;t++){
int xx = i + dir[t][0];
int yy = j + dir[t][1];
area += dfs(land,xx,yy);
}
return area;
}
vector<int> pondSizes(vector<vector<int>>& land) {
if(land.empty()||land[0].empty()){
return {};
}
row = land.size();
col = land[0].size();
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(land[i][j]==0){
res.push_back(dfs(land,i,j));
}
}
}
sort(res.begin(),res.end());
return res;
}
};
这是自己的解法
class Solution {
private:
vector<int>res;
int dir[8][2] = {{1,0},{-1,0},{0,1},{0,-1},{1,-1},{1,1},{-1,1},{-1,-1}};
int row,col;
public:
void dfs(vector<vector<int>>& land, int i,int j,int&k){
if(i<0||i>land.size()-1||j<0||j>land[0].size()-1||land[i][j]!=0){
return;
}
land[i][j] = 1;
k++;
for(int t=0;t<8;t++){
int xx = i + dir[t][0];
int yy = j + dir[t][1];
dfs(land,xx,yy,k);
// if(land[xx][yy]==0){
// //land[xx][yy] = 1;
// //k++;
// dfs(land,xx,yy,k);
// }
}
return;
}
vector<int> pondSizes(vector<vector<int>>& land) {
if(land.empty()){
return {};
}
int r = land.size();
int c = land[0].size();
int nums = 0;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
nums = 0;
if(land[i][j]==0){
dfs(land,i,j,nums);
res.push_back(nums);
}
}
}
sort(res.begin(),res.end());
return res;
}
};