Skip to content

Commit caeee7c

Browse files
committed
grid search done
1 parent f6b047a commit caeee7c

File tree

1 file changed

+32
-16
lines changed

1 file changed

+32
-16
lines changed

src/com/hackerrank/algorithms/implementation/GridSearch.java

+32-16
Original file line numberDiff line numberDiff line change
@@ -23,29 +23,45 @@ public static void main(String[] args) {
2323
for (int P_i = 0; P_i < r; P_i++) {
2424
P[P_i] = in.next();
2525
}
26-
int count = 0;
27-
int start = -1;
2826

27+
// create 2D array for grid
28+
int grid[][] = new int[R][C];
29+
for (int i = 0; i < R; i++) {
30+
for (int j = 0; j < C; j++) {
31+
grid[i][j] = Character.getNumericValue(G[i].charAt(j));
32+
}
33+
}
34+
35+
// create 2D array for pattern to be searched in grid
36+
int pattern[][] = new int[r][c];
37+
for (int i = 0; i < r; i++) {
38+
for (int j = 0; j < c; j++) {
39+
pattern[i][j] = Character.getNumericValue(P[i].charAt(j));
40+
}
41+
}
42+
43+
// search logic
44+
outerLoop:
2945
for (int G_i = 0; G_i < R; G_i++) {
30-
if ((start = G[G_i].indexOf(P[0], start + 1)) > -1) {
31-
count = 1;
32-
for (int P_i = 1; P_i < r && G_i + P_i < R; P_i++) {
33-
if (G[G_i + P_i].indexOf(P[P_i]) != start) {
34-
break;
46+
for (int G_j = 0; G_j < C; G_j++) {
47+
innerLoop:
48+
for (int P_i = 0; P_i < r && G_i + P_i < R; P_i++) {
49+
for (int P_j = 0; P_j < c && G_j + P_j < C; P_j++) {
50+
if (grid[G_i + P_i][G_j + P_j] != pattern[P_i][P_j]) {
51+
break innerLoop;
52+
} else if (P_i == r - 1 && P_j == c - 1) {
53+
System.out.println("YES");
54+
break outerLoop;
55+
}
3556
}
36-
count++;
57+
3758
}
38-
if (count == r) {
39-
System.out.println("YES");
40-
break;
41-
} else {
42-
G_i = 0;
59+
if (R - G_i < r) { // no. of rows left in grid less than no. of rows in pattern
60+
System.out.println("NO");
61+
break outerLoop;
4362
}
4463
}
4564
}
46-
if (count != r) {
47-
System.out.println("NO");
48-
}
4965
}
5066
}
5167
}

0 commit comments

Comments
 (0)