二维数组的遍历使用foreach
二维数组的遍历使用foreach
public int numWays(int n, int[][] relation, int k) { ways = 0; this.n = n; this.k = k; edges = new ArrayList<>(); //把关系处理成list,类似于图的每个节点能到达的节点的信息都存到list里 for (int i = 0; i < n; i++) { edges.add(new ArrayList<>()); } for (int[] edge : relation) { int src = edge[0]; int dst = edge[1]; edges.get(src).add(dst); } dfs(0, 0); return ways; } private void dfs(int index, int steps) { if (steps == k) { if (index == n - 1) { ways++; } return; } List<Integer> list = edges.get(index); for (int nextIndex : list) { dfs(nextIndex, steps + 1); } }
转发无需备注,如有错误,恳求读者指出,发送到wu13213786609@outlook.com。