-
Notifications
You must be signed in to change notification settings - Fork 22
/
soln.java
37 lines (32 loc) · 1.15 KB
/
soln.java
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
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
while (T-- > 0) {
int n = scan.nextInt();
int m = scan.nextInt();
int [] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = scan.nextInt();
}
System.out.println(isSolvable(array, m, 0) ? "YES" : "NO");
}
scan.close();
}
/* Basically a depth-first search (DFS).
Marks each array value as 1 when visiting (Side-effect: alters array) */
private static boolean isSolvable(int[] array, int m, int i) {
/* Base Cases */
if (i < 0 || array[i] == 1) {
return false;
} else if (i + 1 >= array.length || i + m >= array.length) {
return true;
}
array[i] = 1; // marks as visited
/* Recursive Cases (Tries +m first to try to finish game quickly) */
return isSolvable(array, m, i + m) ||
isSolvable(array, m, i + 1) ||
isSolvable(array, m, i - 1);
}
}