@@ -23,29 +23,45 @@ public static void main(String[] args) {
23
23
for (int P_i = 0 ; P_i < r ; P_i ++) {
24
24
P [P_i ] = in .next ();
25
25
}
26
- int count = 0 ;
27
- int start = -1 ;
28
26
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 :
29
45
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
+ }
35
56
}
36
- count ++;
57
+
37
58
}
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 ;
43
62
}
44
63
}
45
64
}
46
- if (count != r ) {
47
- System .out .println ("NO" );
48
- }
49
65
}
50
66
}
51
67
}
0 commit comments