-
Notifications
You must be signed in to change notification settings - Fork 858
Expand file tree
/
Copy pathTheGridSearch.java
More file actions
86 lines (75 loc) · 1.97 KB
/
Copy pathTheGridSearch.java
File metadata and controls
86 lines (75 loc) · 1.97 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
/**
*
* Problem Statement-
* [The Grid Search](https://www.hackerrank.com/challenges/the-grid-search/problem)
*
*/
package com.javaaid.hackerrank.solutions.generalprogramming.basicprogramming;
import java.util.Scanner;
/**
* @author Kanahaiya Gupta
*
*/
public class TheGridSearch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for (int a0 = 0; a0 < t; a0++) {
int R = in.nextInt();
int C = in.nextInt();
String[] G = new String[R];
for (int G_i = 0; G_i < R; G_i++) {
G[G_i] = in.next();
}
int r = in.nextInt();
int c = in.nextInt();
String[] P = new String[r];
for (int P_i = 0; P_i < r; P_i++) {
P[P_i] = in.next();
}
System.out.println(patternExist(R, G, P) ? "YES" : "NO");
}
in.close();
}
/**
* @param n
* @param grid
* @param pattern
*/
private static boolean patternExist(int n, String[] grid, String[] pattern) {
int pLen = pattern.length;
int gLen = grid.length;
if (pLen > gLen)
return false;
for (int gRow = 0; gRow < gLen - pLen + 1; gRow++) {
String p = pattern[0];
String text = grid[gRow];
for (int gCol = 0; gCol < grid[gRow].length() - p.length() + 1; gCol++) {
int index = text.indexOf(p, gCol);
if (index != -1) {
if (validateStringRecursivelly(grid, pattern, index, p.length(), gRow, 0)) {
return true;
}
} else {
break;
}
}
}
return false;
}
/**
* @param grid
* @param pattern
* @param index
* @param length
* @return
*/
private static boolean validateStringRecursivelly(String[] grid, String[] pattern, int index, int length, int gRow,
int pRow) {
if (!grid[gRow].substring(index, index + length).equals(pattern[pRow]))
return false;
if (pattern.length - 1 == pRow)
return true;
return validateStringRecursivelly(grid, pattern, index, length, gRow + 1, pRow + 1);
}
}