leetcode 水域大小(C++)

    科技2024-05-11  85

    你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。

    示例:

    输入: [ [0,2,1,0], [0,1,0,1], [1,1,0,1], [0,1,0,1] ] 输出: [1,2,4]

    提示:

    0 < len(land) <= 10000 < len(land[i]) <= 1000

    C++

    class Solution { public: void dfs(vector<vector<int>>& land, int i, int j) { for(int k=0;k<8;k++) { int y=i+dy[k]; int x=j+dx[k]; if(y>=0 && y<land.size() && x>=0 && x<land[0].size() && 0==land[y][x]) { count++; land[y][x]=3; dfs(land,y,x); } } } vector<int> pondSizes(vector<vector<int>>& land) { int m=land.size(); int n=land[0].size(); vector<int> res; for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { if(0==land[i][j]) { count=1; land[i][j]=3; dfs(land,i,j); res.push_back(count); } } } sort(res.begin(),res.end()); return res; } private: int dy[8]={-1,-1,-1,0,0,1,1,1}; int dx[8]={-1,0,1,-1,1,-1,0,1}; int count=0; };

     

    Processed: 0.008, SQL: 8