矩阵的遍历
对比
在深度优先和广度优先遍历时,我们经常需要从一个点向上下左右四个方向遍历,因此也就有了如下代码:
注意对比遍历的坐标:
public class TestString { public static int[][] dir = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}}; public static void main(String[] args) { TestString t = new TestString(); t.test(0, 0); } public void test(int row, int col) { for (int[] d : dir) { row += d[0]; col += d[1]; System.out.print("row=" + row); System.out.println(", col=" + col); } System.out.println("+++++++++++++++++++++++++++"); for (int[] d : dir) { System.out.print("row = "); System.out.print(row + d[0]); System.out.print(", col = "); System.out.println( col + d[1]); } } }
结果如下:
row=1, col=0
row=0, col=0
row=0, col=-1
row=0, col=0
+++++++++++++++++++++++++++
row = 1, col = 0
row = -1, col = 0
row = 0, col = -1
row = 0, col = 1
对比可以发现,第二种才是我们需要的,第一种在遍历的时候更改了原始的坐标
深度优先遍历模板
class Solution { public static int[][] dir ={{1,0},{-1,0},{0,-1},{0,1}}; private int m, n; private boolean[][] visited; public int numEnclaves(int[][] grid) { m = grid.length; n = grid[0].length; visited = new boolean[m][n]; for (){ /// dfs() /// } } public void dfs(int[][] grid, int row, int col){ if (row<0 || row >=m || col <0 || col>=n || grid[row][col] == 0 || visited[row][col]){ return; } visited[row][col] = true; for(int[] d: dir){ dfs(grid, row+d[0], col+d[1]); } } }