-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnakeAndLadder.java
More file actions
48 lines (39 loc) · 1.11 KB
/
Copy pathSnakeAndLadder.java
File metadata and controls
48 lines (39 loc) · 1.11 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
package src.Arrays;
import java.util.LinkedList;
import java.util.Queue;
/*
https://www.geeksforgeeks.org/snake-ladder-problem-2/
*/
public class SnakeAndLadder {
public int solution(int[] moves, int target) {
Queue<Entry> queue = new LinkedList<>();
boolean[] visited = new boolean[target];
visited[0] = true;
Entry entry = new Entry(0, 0);
queue.add(entry);
while (!queue.isEmpty()) {
entry = queue.poll();
int v = entry.vertex;
if (v == target - 1) {
break;
}
for (var j = v + 1; j <= (v + 6) && j < target; j++) {
if (!visited[j]) {
visited[j] = true;
int n = moves[j] != -1 ? moves[j] : j;
Entry next = new Entry(n, entry.distance + 1);
queue.add(next);
}
}
}
return entry.distance;
}
}
class Entry {
int vertex;
int distance;
public Entry(int vertex, int distance) {
this.vertex = vertex;
this.distance = distance;
}
}