好久没更新了,终于考完了继续回来刷题
岛屿问题属于最基本的DFS, BFS题目 使用DFS时会遇到如果图太大call stack过深的follow up,此时可以转为使用BFS
下一篇Number of Islands II 中将使用另一种Union Find的做法
public class Solution { public int numIslands(char[][] grid) { if (grid == null || grid.length == 0) { return 0; } int result = 0; int m = grid.length; int n = grid[0].length; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { //if gird[i][j] is not visited if (grid[i][j] == ‘1‘) { bfs(grid, i, j); result++; } } } return result; } private void bfs(char[][] grid, int a, int b) { int[] x = {1, 0, -1, 0}; int[] y = {0, -1, 0, 1}; grid[a][b] = ‘0‘; Queue<Pair> q = new LinkedList<Pair>(); q.offer(new Pair(a, b)); while (!q.isEmpty()) { Pair p = q.poll(); for (int i = 0; i < 4; i++) { int x1 = p.x + y[i]; int x2 = p.y + x[i]; if (x2 >= 0 && x2 < grid[0].length && x1 >= 0 && x1 < grid.length) { if (grid[x1][x2] == ‘1‘) { grid[x1][x2] = ‘0‘; q.offer(new Pair(x1, x2)); } } } } } private class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } private void dfs(char[][] grid, int a, int b) { grid[a][b] = ‘0‘; int[] x = {1, 0, -1, 0}; int[] y = {0, -1, 0, 1}; for (int i = 0; i < 4; i++) { int x1 = a + y[i]; int x2 = b + x[i]; if (x2 >= 0 && x2 < grid[0].length && x1 >= 0 && x1 < grid.length) { if (grid[x1][x2] == ‘1‘) { //grid[x1][x2] = ‘0‘; dfs(grid, x1, x2); } } } } }
时间: 2024-10-25 21:12:58