|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + vector<vector<bool>> visited; |
| 4 | + vector<pair<int, int>> ops; |
| 5 | + int island; |
| 6 | + int neigh; |
| 7 | + int max_i; |
| 8 | + int max_j; |
| 9 | + int islandPerimeter(vector<vector<int>>& grid) { |
| 10 | + visited = vector<vector<bool>>(grid.size(), vector<bool>(grid[0].size(), false)); |
| 11 | + max_i = grid.size(); |
| 12 | + max_j = grid[0].size(); |
| 13 | + island = 0; |
| 14 | + neigh = 0; |
| 15 | + ops = { |
| 16 | + make_pair(-1, 0), |
| 17 | + make_pair(1, 0), |
| 18 | + make_pair(0, -1), |
| 19 | + make_pair(0, 1), |
| 20 | + }; |
| 21 | + for (int i = 0; i < grid.size(); ++i) { |
| 22 | + for (int j = 0; j < grid[i].size(); ++j) { |
| 23 | + if (!visited[i][j]) |
| 24 | + bfs(grid, i, j); |
| 25 | + } |
| 26 | + } |
| 27 | + cout << "island: " << island << ", neigh: " << neigh << endl; |
| 28 | + return island * 4 - neigh; |
| 29 | + } |
| 30 | + bool legal(int i, int j) { |
| 31 | + return i >= 0 && i < max_i && j >= 0 && j < max_j; |
| 32 | + } |
| 33 | + void bfs(vector<vector<int>>& grid, int i, int j) { |
| 34 | + queue<pair<int, int>> q; |
| 35 | + q.push(make_pair(i, j)); |
| 36 | + while(!q.empty()) { |
| 37 | + auto top = q.front(); |
| 38 | + q.pop(); |
| 39 | + if (legal(top.first, top.second) && !visited[top.first][top.second]) { |
| 40 | + visited[top.first][top.second] = true; |
| 41 | + if (grid[top.first][top.second]) { |
| 42 | + island++; |
| 43 | + for (auto op: ops) { |
| 44 | + int new_i = top.first + op.first; |
| 45 | + int new_j = top.second + op.second; |
| 46 | + if (legal(new_i, new_j)) { |
| 47 | + cout << new_i << ", " << new_j << endl; |
| 48 | + q.push(make_pair(new_i, new_j)); |
| 49 | + if (grid[new_i][new_j]) |
| 50 | + neigh++; |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | +}; |
0 commit comments