|
1 | 1 | #include "public.h" |
2 | 2 |
|
3 | | -//208ms, 5.36% |
4 | | -//DFS |
| 3 | +//68ms, 97.55% |
5 | 4 | //注意只有一个岛屿而且没有湖 |
6 | | -//如果岛屿某个方向是边界或者水, 那么将被计算到周长里面 |
| 5 | +//对于岛屿: 每当周围多一个岛它的周长贡献减1, 每个岛的最大周长贡献是4 |
| 6 | +//直接双重循环 |
7 | 7 |
|
8 | 8 | class Solution { |
9 | | -private: |
10 | | - int res = 0; |
11 | | - void DFS(const vector<vector<int>>& grid, vector<vector<bool>>& issearched, |
12 | | - int r, int c) |
13 | | - { |
14 | | - issearched[r][c] = true; |
15 | | - if (r == 0) res++; |
16 | | - else |
17 | | - { |
18 | | - if (grid[r - 1][c] == 0) res++; |
19 | | - else if (!issearched[r - 1][c]) DFS(grid, issearched, r - 1, c); |
20 | | - } |
21 | | - |
22 | | - if (c == 0) res++; |
23 | | - else |
24 | | - { |
25 | | - if (grid[r][c - 1] == 0) res++; |
26 | | - else if (!issearched[r][c - 1]) DFS(grid, issearched, r, c - 1); |
27 | | - } |
28 | | - |
29 | | - if (r == grid.size() - 1) res++; |
30 | | - else |
31 | | - { |
32 | | - if (grid[r + 1][c] == 0) res++; |
33 | | - else if (!issearched[r + 1][c]) DFS(grid, issearched, r + 1, c); |
34 | | - } |
35 | | - |
36 | | - if (c == grid[0].size() - 1) res++; |
37 | | - else |
38 | | - { |
39 | | - if (grid[r][c + 1] == 0) res++; |
40 | | - else if (!issearched[r][c + 1]) DFS(grid, issearched, r, c + 1); |
41 | | - } |
42 | | - } |
43 | | - |
44 | 9 | public: |
45 | 10 | int islandPerimeter(vector<vector<int>>& grid) { |
46 | | - vector<vector<bool>> issearched(grid.size(), vector<bool>(grid[0].size(), false)); |
47 | | - //找到一块陆地, DFS |
48 | | - for (int r = 0; r < grid.size(); ++r) |
49 | | - for (int c = 0; c < grid[0].size(); ++c) |
| 11 | + int res = 0; |
| 12 | + int gSize = grid.size(); |
| 13 | + int g0Size = grid[0].size(); |
| 14 | + for (int r = 0; r < gSize; ++r) |
| 15 | + for (int c = 0; c < g0Size; ++c) |
| 16 | + { |
50 | 17 | if (grid[r][c] == 1) |
51 | 18 | { |
52 | | - DFS(grid, issearched, r, c); |
53 | | - goto bigbreak; |
| 19 | + int contribute = 4; |
| 20 | + if (r > 0 && grid[r - 1][c] == 1) contribute--; |
| 21 | + if (c > 0 && grid[r][c - 1] == 1) contribute--; |
| 22 | + if (r < (gSize - 1)&& grid[r + 1][c] == 1) contribute--; |
| 23 | + if (c < (g0Size - 1) && grid[r][c + 1] == 1) contribute--; |
| 24 | + res += contribute; |
54 | 25 | } |
55 | | - bigbreak: |
| 26 | + } |
56 | 27 | return res; |
57 | 28 | } |
58 | 29 | }; |
|
0 commit comments