mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
解決跑板問題 + 提供java解法(和卡哥邏輯一致)
跑版: 原本的code box 結束的```不見了,所以看不到結尾圖片。 新解法和原本JAVA解法的差異: 原版的應該是自己寫的DFS,邏輯大致一致,但還是有差異,故提供用卡哥C++ code改的版本
This commit is contained in:
@ -176,6 +176,48 @@ public void dfs(char[][] grid, int i, int j){
|
||||
dfs(grid,i,j + 1);
|
||||
dfs(grid,i,j - 1);
|
||||
}
|
||||
```
|
||||
```java
|
||||
//graph - dfs (和卡哥的代碼邏輯一致)
|
||||
class Solution {
|
||||
boolean[][] visited;
|
||||
int dir[][] = {
|
||||
{0, 1}, //right
|
||||
{1, 0}, //down
|
||||
{-1, 0}, //up
|
||||
{0, -1} //left
|
||||
};
|
||||
public int numIslands(char[][] grid) {
|
||||
int count = 0;
|
||||
visited = new boolean[grid.length][grid[0].length];
|
||||
|
||||
for(int i = 0; i < grid.length; i++){
|
||||
for(int j = 0; j < grid[0].length; j++){
|
||||
if(visited[i][j] == false && grid[i][j] == '1'){
|
||||
count++;
|
||||
dfs(grid, i, j);
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private void dfs(char[][]grid, int x, int y){
|
||||
if(visited[x][y] == true || grid[x][y] == '0')
|
||||
return;
|
||||
|
||||
visited[x][y] = true;
|
||||
|
||||
for(int i = 0; i < 4; i++){
|
||||
int nextX = x + dir[i][0];
|
||||
int nextY = y + dir[i][1];
|
||||
if(nextX < 0 || nextY < 0 || nextX >= grid.length || nextY >= grid[0].length)
|
||||
continue;
|
||||
dfs(grid, nextX, nextY);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
|
Reference in New Issue
Block a user