其他分享
首页 > 其他分享> > 二维数组的遍历使用foreach

二维数组的遍历使用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);
            }

        }

 

标签:index,遍历,int,list,dfs,ways,二维,edges,foreach
来源: https://www.cnblogs.com/WLCYSYS/p/14978889.html