1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| class Solution { public: int islandPerimeter(vector<vector<int>>& grid) { return perimeterOfMaxArea(grid); } private: vector<vector<int>> dir{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int same_cnt = 0;
int perimeterOfMaxArea(vector<vector<int>>& map) { int rows = map.size(); if (rows == 0) return 0; int cols = map[0].size();
int ret = 0; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { same_cnt = 0; int one_cnt = dfs(map, i, j); ret = max(ret, one_cnt * 4 - same_cnt * 2); } }
return ret; }
int dfs(vector<vector<int>>& map, int i, int j) { int rows = map.size(); int cols = map[0].size();
if (i < 0 || i >= rows || j < 0 || j >= cols) return 0;
if (map[i][j] == 0) return 0;
int one_cnt = 1;
for (auto& d : dir) { int row = i + d[0], col = j + d[1]; if (row < 0 || row >= rows || col < 0 || col >= cols || map[row][col] == 0) continue; ++same_cnt; } map[i][j] = 0; for (auto& d : dir) { int row = i + d[0], col = j + d[1]; one_cnt += dfs(map, row, col); }
return one_cnt; } };
|