diff --git a/problems/1020.飞地的数量.md b/problems/1020.飞地的数量.md index e92b2412..7538d774 100644 --- a/problems/1020.飞地的数量.md +++ b/problems/1020.飞地的数量.md @@ -149,7 +149,63 @@ public: ### Java -深度优先遍历版本: +深度优先遍历(没有终止条件 + 空間優化(淹沒島嶼,沒有使用visited數組)) +```java +//DFS +class Solution { + int count = 0; + int[][] dir ={ + {0, 1}, + {1, 0}, + {-1, 0}, + {0, -1} + }; + private void dfs(int[][] grid, int x, int y){ + if(grid[x][y] == 0) + return; + + grid[x][y] = 0; + count++; + + 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); + } + + } + + public int numEnclaves(int[][] grid) { + for(int i = 0; i < grid.length; i++){ + if(grid[i][0] == 1) + dfs(grid, i, 0); + if(grid[i][grid[0].length - 1] == 1) + dfs(grid, i, grid[0].length - 1); + } + //初始化的時候,j 的上下限有調整過,必免重複操作。 + for(int j = 1; j < grid[0].length - 1; j++){ + if(grid[0][j] == 1) + dfs(grid, 0, j); + if(grid[grid.length - 1][j] == 1) + dfs(grid, grid.length - 1, j); + } + count = 0; + + for(int i = 1; i < grid.length - 1; i++){ + for(int j = 1; j < grid[0].length - 1; j++){ + if(grid[i][j] == 1) + dfs(grid, i, j); + } + } + return count; + } +} +``` + +深度优先遍历(没有终止条件) ```java class Solution { @@ -206,7 +262,7 @@ class Solution { } ``` -广度优先遍历版本: +广度优先遍历(使用visited數組) ```java class Solution { @@ -269,6 +325,72 @@ class Solution { } ``` +廣度优先遍历(空間優化(淹沒島嶼,沒有使用visited數組)) +```java +//BFS +class Solution { + int count = 0; + int[][] dir ={ + {0, 1}, + {1, 0}, + {-1, 0}, + {0, -1} + }; + private void bfs(int[][] grid, int x, int y){ + Queue que = new LinkedList<>(); + que.offer(x); + que.offer(y); + count++; + grid[x][y] = 0; + + while(!que.isEmpty()){ + int currX = que.poll(); + int currY = que.poll(); + + for(int i = 0; i < 4; i++){ + int nextX = currX + dir[i][0]; + int nextY = currY + dir[i][1]; + + if(nextX < 0 || nextY < 0 || nextX >= grid.length || nextY >= grid[0].length) + continue; + + if(grid[nextX][nextY] == 1){ + que.offer(nextX); + que.offer(nextY); + count++; + grid[nextX][nextY] = 0; + } + } + } + } + + public int numEnclaves(int[][] grid) { + for(int i = 0; i < grid.length; i++){ + if(grid[i][0] == 1) + bfs(grid, i, 0); + if(grid[i][grid[0].length - 1] == 1) + bfs(grid, i, grid[0].length - 1); + } + for(int j = 1; j < grid[0].length; j++){ + if(grid[0][j] == 1) + bfs(grid, 0 , j); + if(grid[grid.length - 1][j] == 1) + bfs(grid, grid.length - 1, j); + } + count = 0; + for(int i = 1; i < grid.length - 1; i++){ + for(int j = 1; j < grid[0].length - 1; j++){ + if(grid[i][j] == 1) + bfs(grid,i ,j); + } + } + return count; + } +} + + +``` + ### Python 深度优先遍历