用size控制广度优先搜索一次遍历一行即可实现计数。

玛雅人的密码

https://www.nowcoder.com/practice/761fc1e2f03742c2aa929c19ba96dbb0

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Label:
        while (sc.hasNextInt()) {
            int n = sc.nextInt();
            StringBuilder s = new StringBuilder(sc.next());
            Queue<StringBuilder> queue = new LinkedList<>();
            Set<StringBuilder> isVisited = new HashSet<>();
            queue.offer(s);
            isVisited.add(s);
            int count = 0;
            while (!queue.isEmpty()) {
                int size = queue.size();
                while (size-- > 0) {
                    StringBuilder cur = queue.poll();
                    if (cur.toString().contains("2012")) {
                        System.out.println(count);
                        continue Label;
                    }
                    for (int i = 1; i < n; i++) {
                        StringBuilder next = new StringBuilder(cur);
                        swap(next, i, i - 1);
                        if (!isVisited.contains(next)) {
                            queue.offer(next);
                            isVisited.add(next);
                        }
                    }
                }
                count++;
            }
            System.out.println(-1);
        }
    }
    private static void swap(StringBuilder s, int i, int j) {
        char temp = s.charAt(i);
        s.setCharAt(i, s.charAt(j));
        s.setCharAt(j, temp);
    }
}

全部评论

相关推荐

10-04 17:25
门头沟学院 Java
snqing:Java已经饱和了,根本不缺人。随便一个2000工资的都200人起投递
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务