雙向廣搜
例題:190. 字串變換
有錯…
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Scanner;
public class Main {
static int N = 6;
static int n;
static String[] a = new String[N];
static String[] b = new String[N];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String A = sc.next();
String B = sc.next();
while (sc.hasNext()) {
a[n] = sc.next();
b[n] = sc.next();
n++;
}
int step = bfs(A, B);
if (step > 10) {
System.out.println("NO ANSWER!");
} else {
System.out.println(step);
}
}
private static int bfs(String A, String B) {
LinkedList<String> qa = new LinkedList<>();
LinkedList<String> qb = new LinkedList<>();
Map<String, Integer> da = new HashMap<>();
Map<String, Integer> db = new HashMap<>();
qa.add(A);
qb.add(B);
da.put(A, 0);
db.put(B, 1);
while (qa.size() > 0 && qb.size() > 0) {
if (da.get(qa.peek()) + db.get(qb.peek()) > 10) return 11;
int t;
if (qa.size() <= qb.size()) t = extend(qa, da, db, a, b);
else t = extend(qb, db, da, b, a);
if (t != -1) return t;
}
return 11;
}
private static int extend(LinkedList<String> q, Map<String, Integer> da, Map<String, Integer> db, String[] a, String[] b) {
String t = q.poll();
for (int i = 0; i < t.length(); i++) {
for (int j = 0; j < n; j++) {
if (!t.substring(i, a[j].length()).equals(a[j])) continue;
String r = t.substring(0, i) + b[j] + t.substring(i + a[j].length());
if (db.containsKey(r)) return db.get(r) + da.get(t);
if (da.containsKey(r)) continue;
da.put(r, da.get(t) + 1);
q.add(r);
}
}
return -1;
}
}