-
Notifications
You must be signed in to change notification settings - Fork 0
/
Java 1D Array (Part 2)
84 lines (74 loc) · 2.11 KB
/
Java 1D Array (Part 2)
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
/* Sample Input
STDIN Function
----- --------
4 q = 4 (number of queries)
5 3 game[] size n = 5, leap = 3 (first query)
0 0 0 0 0 game = [0, 0, 0, 0, 0]
6 5 game[] size n = 6, leap = 5 (second query)
0 0 0 1 1 1 . . .
6 3
0 0 1 1 1 0
3 1
0 1 0
Sample Output
YES
YES
NO
NO */
code
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < t; i++) {
int n = scanner.nextInt();
int m = scanner.nextInt();
//System.out.println(n + " " + m);
int[] arr = new int[n];
for (int j = 0; j < n; j++) {
arr[j] = scanner.nextInt();
//System.out.print(arr[j]);
}
//System.out.println();
solve(n,m,arr);
}
}
public static void solve(int n, int m, int[] arr) {
if (solve(n,m,arr,new boolean[n],0)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
public static boolean solve(int n, int m, int[] arr, boolean[] visited, int curr) {
if (curr + m >= n || curr + 1 == n) {
return true;
}
boolean[] newVisited = new boolean[n];
for (int i = 0; i < n; i++) {
newVisited[i] = visited[i];
}
boolean s = false;
if (!visited[curr+1] && arr[curr+1] == 0) {
newVisited[curr+1] = true;
s = solve(n,m,arr,newVisited,curr+1);
}
if (s) {
return true;
}
if (m > 1 && arr[curr+m] == 0 && !visited[curr+m]) {
newVisited[curr+m] = true;
s = solve(n,m,arr,newVisited,curr+m);
}
if (s) {
return true;
}
if (curr > 0 && arr[curr-1] == 0 && !visited[curr-1]) {
newVisited[curr-1] = true;
s = solve(n,m,arr,newVisited,curr-1);
}
return s;
}
}