AcWing 845. 八数码 java -手写hash
原题链接
中等
作者:
usw
,
2020-05-19 23:09:59
,
所有人可见
,
阅读 678
import java.io.*;
import java.util.*;
public class Main {
static int N = 200003;
static int bound = (int) 1e9 + 1;
static int[] h = new int[N];
static int[] ha = new int[N];
static long mod = Long.MAX_VALUE;
static int pre = 1331;
static int find(int x) {
int k = (x % N + N) % N;
while (h[k] != bound && h[k] != x) {
k++;
if (k == N)
k = 0;
}
return k;
}
static int bfs(String start, String end) {
Queue<pairs> q = new LinkedList<>();
q.add(new pairs(start, 0));
int[] dx = { -1, 0, 1, 0 }, dy = { 0, 1, 0, -1 };
while (!q.isEmpty()) {
pairs s = q.poll();
hash(s.string);
h[find(ha[9])] = ha[9];
if (s.string.equals(end)) {
return s.distance;
}
String str = s.string;
int k = str.indexOf('x');
int x = k / 3, y = k % 3;
for (int i = 0; i < 4; i++) {
int a = x + dx[i];
int b = y + dy[i];
if (a >= 0 && a < 3 && b >= 0 && b < 3) {
char[] c = str.toCharArray();
swap(c, k, a * 3 + b);
String str2 = new String(c);
hash(str2);
if (h[find(ha[9])] == bound) {
q.add(new pairs(str2, s.distance+1));
}
}
}
}
return -1;
}
static void hash(String str) {
int len = str.length();
for (int i = 1; i <= len; i++) {
ha[i] = (int) (ha[i - 1] * pre + (str.charAt(i - 1)) % mod);
}
}
static void swap(char[] s, int x, int x1) {
char temp = s[x];
s[x] = s[x1];
s[x1] = temp;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s = br.readLine().split(" ");
String start = "";
for (String x : s) {
start += x;
}
String end = "12345678x";
Arrays.fill(h, bound);
System.out.println(bfs(start, end));
}
}
class pairs {
String string;
int distance;
public pairs(String s, int x) {
this.string = s;
this.distance = x;
}
}