-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLab1Sub3.java
More file actions
97 lines (75 loc) · 2.42 KB
/
Lab1Sub3.java
File metadata and controls
97 lines (75 loc) · 2.42 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
91
92
93
94
95
96
97
import java.util.*;
public class Lab1Sub3 {
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(bfs(start, goal));
in.close();
}
public static int bfs(String start, String goal) {
Queue<Node> queue = new LinkedList<>();
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)) {
// for BFS every move costs 1 step regardless of direction
queue.add(new Node(mv.state, current.cost + 1));
}
}
return -1;
}
static class Node {
String state;
int cost;
Node(String s, int c) {
state = s;
cost = c;
}
}
static class Move {
String state;
int moveCost; // not used by BFS but kept for same structure
Move(String s, int c) {
state = s;
moveCost = c;
}
}
public static List<Move> neighbors(String state) {
List<Move> result = new ArrayList<>();
int blank = state.indexOf('#');
int row = blank / 3;
int col = blank % 3;
// UP
if (row > 0) {
result.add(new Move(apply(state, row, col, row - 1, col), 1));
}
// DOWN
if (row < 2) {
result.add(new Move(apply(state, row, col, row + 1, col), 1));
}
// LEFT
if (col > 0) {
result.add(new Move(apply(state, row, col, row, col - 1), 1));
}
// RIGHT
if (col < 2) {
result.add(new Move(apply(state, row, col, row, col + 1), 1));
}
return result;
}
public static String apply(String state, int r1, int c1, int r2, int c2) {
int i1 = r1 * 3 + c1;
int i2 = r2 * 3 + c2;
char[] arr = state.toCharArray();
arr[i1] = arr[i2];
arr[i2] = '#';
return new String(arr);
}
}