您的位置:首页 > 博客中心 > 编程语言 >

二维数组的遍历使用foreach

时间:2022-03-29 01:54

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

        }

 

本类排行

今日推荐

热门手游