-
Notifications
You must be signed in to change notification settings - Fork 694
/
Copy pathSolution.java
88 lines (78 loc) · 3.03 KB
/
Solution.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
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
87
88
//Problem: https://www.hackerrank.com/challenges/the-grid-search
//Java 8
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner input = new Scanner(System.in);
int T = input.nextInt();
tests:
for(int t = 0; t < T; t++)
{
/* INITIALIZE GRID AND PATTERN */
/////////////////////////////////////////////////////////////////
int R = input.nextInt();
int C = input.nextInt();
input.nextLine();
int[][] Grid = new int[R][C];
for(int i = 0; i < R; i++)
{
String row = input.nextLine();
for(int j = 0; j < C; j++)
{
Grid[i][j] = Character.getNumericValue(row.charAt(j));
}
}
int r = input.nextInt();
int c = input.nextInt();
input.nextLine();
int[][] Pattern = new int[r][c];
for(int i = 0; i < r; i++)
{
String row = input.nextLine();
for(int j = 0; j < c; j++)
{
Pattern[i][j] = Character.getNumericValue(row.charAt(j));
}
}
///////////////////////////////////////////////////////////////////
int PatternStart = Pattern[0][0];
for(int i = 0; i < Grid.length; i++)
{
for(int j = 0; j < Grid[0].length; j++)
{
if(Grid[i][j] == PatternStart)
{
//Perform a pattern search
if(isPattern(Grid, i, j, Pattern))
{
System.out.println("YES");
continue tests;
}
}
}
}
System.out.println("NO");
}
}
//Checks if the pattern matches to the section in grid
public static boolean isPattern(int[][] Grid, int i, int j, int[][] Pattern)
{
if(i > Grid.length-Pattern.length || j > Grid[0].length-Pattern[0].length){return false;} //Returns false if the pattern
//can't even fit
int rowG = i;
int colG = j;
for(int rowP = 0; rowP < Pattern.length; rowP++)
{
for(int colP = 0; colP < Pattern[0].length; colP++)
{
if(Grid[rowG][colG] != Pattern[rowP][colP]){return false;}
colG++;
}
colG = j;
rowG++;
}
return true; //Pattern matched in every case
}
}