|
| 1 | +/// Source : https://leetcode.cn/problems/pond-sizes-lcci/ |
| 2 | +/// Author : liuyubobobo |
| 3 | +/// Time : 2023-06-22 |
| 4 | + |
| 5 | +#include <iostream> |
| 6 | +#include <vector> |
| 7 | +#include <algorithm> |
| 8 | + |
| 9 | +using namespace std; |
| 10 | + |
| 11 | + |
| 12 | +/// DFS |
| 13 | +/// Time Complexity: O(R * C) |
| 14 | +/// Space Complexity: O(R * C) |
| 15 | +class Solution { |
| 16 | + |
| 17 | +private: |
| 18 | + int R, C; |
| 19 | + const int dirs[8][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, |
| 20 | + {-1, -1}, {-1, 1}, {1, -1}, {1, 1}}; |
| 21 | + |
| 22 | +public: |
| 23 | + vector<int> pondSizes(vector<vector<int>>& land) { |
| 24 | + |
| 25 | + R = land.size(); C = land[0].size(); |
| 26 | + vector<vector<bool>> visited(R, vector<bool>(C, false)); |
| 27 | + vector<int> res; |
| 28 | + for(int i = 0; i < R; i ++) |
| 29 | + for(int j = 0; j < C; j ++){ |
| 30 | + if(visited[i][j] || land[i][j]) continue; |
| 31 | + res.push_back(dfs(land, i, j, visited)); |
| 32 | + } |
| 33 | + sort(res.begin(), res.end()); |
| 34 | + return res; |
| 35 | + } |
| 36 | + |
| 37 | +private: |
| 38 | + int dfs(const vector<vector<int>>& land, int cx, int cy, vector<vector<bool>>& visited){ |
| 39 | + |
| 40 | + visited[cx][cy] = true; |
| 41 | + int res = 1; |
| 42 | + for(int d = 0; d < 8; d ++){ |
| 43 | + int nx = cx + dirs[d][0], ny = cy + dirs[d][1]; |
| 44 | + if(in_area(nx, ny) && !visited[nx][ny] && !land[nx][ny]) |
| 45 | + res += dfs(land, nx, ny, visited); |
| 46 | + } |
| 47 | + return res; |
| 48 | + } |
| 49 | + |
| 50 | + bool in_area(int x, int y){ |
| 51 | + return 0 <= x && x < R && 0 <= y && y < C; |
| 52 | + } |
| 53 | +}; |
| 54 | + |
| 55 | + |
| 56 | +int main() { |
| 57 | + |
| 58 | + return 0; |
| 59 | +} |
0 commit comments