diff --git "a/problems/kamacoder/0101.\345\255\244\345\262\233\347\232\204\346\200\273\351\235\242\347\247\257.md" "b/problems/kamacoder/0101.\345\255\244\345\262\233\347\232\204\346\200\273\351\235\242\347\247\257.md" index b3f66b96d8..d2d23baaa1 100644 --- "a/problems/kamacoder/0101.\345\255\244\345\262\233\347\232\204\346\200\273\351\235\242\347\247\257.md" +++ "b/problems/kamacoder/0101.\345\255\244\345\262\233\347\232\204\346\200\273\351\235\242\347\247\257.md" @@ -184,8 +184,78 @@ int main() { ### Java +#### 深搜版 ``` java +import java.util.*; + +public class Main { + //接收矩阵所用到的图 + public static int[][] grid; + //遍历上下左右四个方向的数组 + public static int[][] direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + //最终结果 + public static int result = 0; + + public static void dfs(int x, int y) { + //将陆地变为海洋 + grid[x][y] = 0; + + for (int i = 0; i < 4; i++) { + //下一个x坐标 + int nextX = x + direction[i][0]; + //下一个y坐标 + int nextY = y + direction[i][1]; + //确保坐标位置访问不会越界 + if (nextX < 0 || nextX >= grid.length || nextY < 0 || nextY >= grid[0].length) continue; + //如果下一个坐标位置是陆地, 则继续递归将周围的陆地变为海洋 + if (grid[nextX][nextY] == 1) { + dfs(nextX, nextY); + } + } + } + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + int m = sc.nextInt(); + + grid = new int[n][m]; + + //填充grid图 + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + grid[i][j] = sc.nextInt(); + } + } + //遍历行方向的两条边 + for (int i = 0; i < n; i++) { + //如果是岛屿则将当前岛屿以及周围的岛屿都变为海洋 + if (grid[i][0] == 1) dfs(i, 0); + if (grid[i][m - 1] == 1) dfs(i, m - 1); + } + //遍历列方向的两条边 + for (int j = 0; j < m; j++) { + if (grid[0][j] == 1) dfs(0, j); + + if (grid[n - 1][j] == 1) dfs(n - 1, j); + } + //遍历累加结果 + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (grid[i][j] == 1) { + result++; + } + } + } + //打印结果 + System.out.println(result); + } +} +``` + +#### 广搜版 +``` java import java.util.*; public class Main { @@ -249,9 +319,6 @@ public class Main { System.out.println(count); } } - - - ```