本文共 3143 字,大约阅读时间需要 10 分钟。
为了解决这个问题,我们需要找到将给定网格中的“x”移动到指定位置所需的最少交换次数。我们可以使用广度优先搜索(BFS)来探索所有可能的交换状态,从而找到最短路径。
import java.io.BufferedReader;import java.io.IOException;import java.util.ArrayDeque;import java.util.Deque;import java.util.HashMap;import java.util.Map;class Main { static final String START = "12345678x"; static final String[] DIRECTIONS = { "-1,0,0,-1", "1,0,0,1", "0,-1,-1,0", "0,1,1,1" }; static final int[][] D = new int[][] { {-1, 0, 0, 0}, {1, 0, 0, 0}, {0, 0, -1, 1}, {0, 0, 1, -1} }; static final String[] dx = { "-1", "1", "0", "0" }; static final String[] dy = { "0", "0", "-1", "1" }; static Map d = new HashMap<>(); static Map strsh = new HashMap<>(); static Map pre = new HashMap<>(); static Deque q = new ArrayDeque<>(); static int idx = 0; static int res = -1; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = br.readLine(); input = input.replace(" ", ""); System.out.println(bfs(input)); } private static int bfs(String start) { q.clear(); d.clear(); strsh.clear(); pre.clear(); if (start.equals(START)) return 0; q.add(start); d.put(start, 0); strsh.put(start, idx); pre.put(start, null); idx++; String target = START; while (!q.isEmpty()) { String current = q.poll(); if (current.equals(target)) { for (int i = res; i != -1; i = pre.get(i)) { res = pre.get(i); if (res == null) break; } return d.get(current); } int x = current.indexOf('x'); if (x == -1) continue; int x_row = x / 3; int x_col = x % 3; for (int i = 0; i < 4; i++) { int new_row = x_row + D[i][0]; int new_col = x_col + D[i][1]; if (new_row < 0 || new_row >= 3 || new_col < 0 || new_col >= 3) continue; String[] chars = current.toCharArray(); chars[x], chars[new_row * 3 + new_col] = chars[new_row * 3 + new_col], chars[x]; String next = new String(chars); if (!d.containsKey(next)) { d.put(next, d.get(current) + 1); strsh.put(next, idx); pre.put(next, current); idx++; q.add(next); if (next.equals(target)) { res = idx; } } } } return -1; }} 通过这种方法,我们可以有效地探索所有可能的交换状态,找到最少交换次数。
转载地址:http://iure.baihongyu.com/