出牌数量-bfs

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] line1 = scanner.nextLine().split(" ");
        String[] line2 = scanner.nextLine().split(" ");

        String[][] map = new String[line1.length][2];
        for (int i = 0; i < line1.length; i++) {
            map[i][0] = line1[i];
            map[i][1] = line2[i];
        }

        ArrayList<Integer> resArr = new ArrayList<>();
        for (int i = 0; i < map.length; i++) {
            int start = i;
            int res = bfs(map,start);
            resArr.add(res);
        }
//        resArr.sort(Integer::compare);
        System.out.println(resArr);

    }

    private static int bfs(String[][] map, int start) {
        int n = map.length;
        Queue<Integer> queue = new ArrayDeque<>();
        Set<Integer> visited = new HashSet<>();
        queue.offer(start);
        visited.add(start);
        int current = -1;
        int res = 0;
        while (!queue.isEmpty()) {
            current = queue.poll();
            String num = map[current][0];
            String color = map[current][1];

            for (int i = 0; i < n; i++) {
                if (visited.contains(i)) {
                    continue;
                }
                String newNum = map[i][0];
                String newColor = map[i][1];
                if (newNum.equals(num) || newColor.equals(color)) {
                    queue.offer(i);
                    visited.add(i);
                }
            }
            res++;
        }
        return res;
    }

全部评论
bfs这类问题一般都比较复杂
点赞 回复 分享
发布于 2022-08-05 10:49

相关推荐

专业码bug百年:整个宇宙为你而闪烁
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务