-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUCS.java
More file actions
90 lines (70 loc) · 2.33 KB
/
UCS.java
File metadata and controls
90 lines (70 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.util.*;
public class UCS {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String start = in.nextLine().trim();
String goal = in.nextLine().trim();
System.out.println(ucs(start, goal));
in.close();
}
static class Node {
String state;
int cost;
Node(String s, int c) {
state = s;
cost = c;
}
}
static class Move {
String state;
int moveCost;
Move(String s, int c) {
state = s;
moveCost = c;
}
}
public static int ucs(String start, String goal) {
PriorityQueue<Node> queue = new PriorityQueue<>(Comparator.comparingInt(n -> n.cost));
Set<String> visited = new HashSet<>();
queue.add(new Node(start, 0));
while (!queue.isEmpty()) {
Node current = queue.poll();
if (visited.contains(current.state))
continue;
visited.add(current.state);
if (current.state.equals(goal))
return current.cost;
for (Move mv : neighbors(current.state)) {
queue.add(new Node(mv.state, current.cost + mv.moveCost));
}
}
return -1;
}
public static List<Move> neighbors(String state) {
List<Move> results = new ArrayList<>();
int blank = state.indexOf('#');
int row = blank / 3;
int col = blank % 3;
if (row > 0) {
results.add(new Move(apply(state, row, col, row - 1, col), 5));
}
if (row < 2) {
results.add(new Move(apply(state, row, col, row + 1, col), 1));
}
if (col > 0) {
results.add(new Move(apply(state, row, col, row, col - 1), 1));
}
if (col < 2) {
results.add(new Move(apply(state, row, col, row, col + 1), 1));
}
return results;
}
public static String apply(String state, int row, int col, int row1, int col1) {
int blank = row * 3 + col;
int newPos = row1 * 3 + col1;
char[] tiles = state.toCharArray();
tiles[blank] = tiles[newPos];
tiles[newPos] = '#';
return new String(tiles);
}
}