Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6cd9b16

Browse files
新增java DFS解法當作延伸
1 parent 496f80d commit 6cd9b16

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

‎problems/0463.岛屿的周长.md‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,53 @@ class Solution {
142142
return landSum * 4 - cover * 2;
143143
}
144144
}
145+
// 延伸 - 傳統DFS解法(使用visited數組)(遇到邊界 或是 海水 就edge ++)
146+
class Solution {
147+
int dir[][] ={
148+
{0, 1},
149+
{0, -1},
150+
{1, 0},
151+
{-1, 0}
152+
};
153+
154+
boolean visited[][];
155+
int res = 0;
156+
157+
public int islandPerimeter(int[][] grid) {
158+
int row = grid.length;
159+
int col = grid[0].length;
160+
visited = new boolean[row][col];
161+
162+
int result = 0;
163+
164+
for(int i = 0; i < row; i++){
165+
for(int j = 0; j < col; j++){
166+
if(visited[i][j] == false && grid[i][j] == 1)
167+
result += dfs(grid, i, j);
168+
}
169+
}
170+
return result;
171+
}
172+
173+
private int dfs(int[][] grid, int x, int y){
174+
//如果遇到 邊界(x < 0 || y < 0 || x >= grid.length || y >= grid[0].length)或是 遇到海水(grid[x][y] == 0)就return 1(edge + 1)
175+
if(x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || grid[x][y] == 0)
176+
return 1;
177+
//如果該地已經拜訪過,就return 0 避免重複計算
178+
if(visited[x][y])
179+
return 0;
180+
int temp = 0;
181+
visited[x][y] = true;
182+
for(int i = 0; i < 4; i++){
183+
int nextX = x + dir[i][0];
184+
int nextY = y + dir[i][1];
185+
//用temp 把edge存起來
186+
temp +=dfs(grid, nextX, nextY);
187+
}
188+
return temp;
189+
}
190+
}
191+
145192
```
146193

147194
Python:

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /