用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); } }