mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
@ -142,6 +142,53 @@ class Solution {
|
||||
return landSum * 4 - cover * 2;
|
||||
}
|
||||
}
|
||||
// 延伸 - 傳統DFS解法(使用visited數組)(遇到邊界 或是 海水 就edge ++)
|
||||
class Solution {
|
||||
int dir[][] ={
|
||||
{0, 1},
|
||||
{0, -1},
|
||||
{1, 0},
|
||||
{-1, 0}
|
||||
};
|
||||
|
||||
boolean visited[][];
|
||||
int res = 0;
|
||||
|
||||
public int islandPerimeter(int[][] grid) {
|
||||
int row = grid.length;
|
||||
int col = grid[0].length;
|
||||
visited = new boolean[row][col];
|
||||
|
||||
int result = 0;
|
||||
|
||||
for(int i = 0; i < row; i++){
|
||||
for(int j = 0; j < col; j++){
|
||||
if(visited[i][j] == false && grid[i][j] == 1)
|
||||
result += dfs(grid, i, j);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private int dfs(int[][] grid, int x, int y){
|
||||
//如果遇到 邊界(x < 0 || y < 0 || x >= grid.length || y >= grid[0].length)或是 遇到海水(grid[x][y] == 0)就return 1(edge + 1)
|
||||
if(x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || grid[x][y] == 0)
|
||||
return 1;
|
||||
//如果該地已經拜訪過,就return 0 避免重複計算
|
||||
if(visited[x][y])
|
||||
return 0;
|
||||
int temp = 0;
|
||||
visited[x][y] = true;
|
||||
for(int i = 0; i < 4; i++){
|
||||
int nextX = x + dir[i][0];
|
||||
int nextY = y + dir[i][1];
|
||||
//用temp 把edge存起來
|
||||
temp +=dfs(grid, nextX, nextY);
|
||||
}
|
||||
return temp;
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Python:
|
||||
|
Reference in New Issue
Block a user