Java program to Search sub array inside an array
Same Problems:
Java 2D array Grid Search
Search sub array inside a array
Grid Search
multidimensional array search
Example:
m1 = 1 2 5 5 6 5 0
5 2 10 5 6 5 4
9 2 34 0 2 9 6
1 2 5 5 6 5 6
8 2 11 5 6 1 3
9 2 34 0 2 9 2
search array :
m2 : 0 2 9
5 6 5
5 6 1
Solution:
Java 2D array Grid Search
Search sub array inside a array
Grid Search
multidimensional array search
Example:
m1 = 1 2 5 5 6 5 0
5 2 10 5 6 5 4
9 2 34 0 2 9 6
1 2 5 5 6 5 6
8 2 11 5 6 1 3
9 2 34 0 2 9 2
search array :
m2 : 0 2 9
5 6 5
5 6 1
Solution:
- import java.io.*;
- import java.util.*;
- import java.text.*;
- import java.math.*;
- import java.util.regex.*;
- public class Solution {
- public static void main(String[] args)
- {
- /--------------------Input------ see Note--------------------
- Scanner scan = new Scanner(System.in);
- int steps = Integer.parseInt(scan.nextLine());
- while(steps >0){
- int sr = scan.nextInt();
- int sc = scan.nextInt();
- boolean found = false;
- scan.nextLine();
- int[][] m1 = new int[sr][sc];
- for(int i=0;i<sr;i++){
- String row = scan.nextLine();
- for(int j=0;j<sc;j++){
- m1[i][j] = (int)(row.charAt(j) );
- }
- }
- /--------------------Input End--------------------------
- int fr = scan.nextInt();
- int fc = scan.nextInt();
- scan.nextLine();
- int[][] m2 = new int[fr][fc];
- for(int i=0;i<fr;i++){
- String row = scan.nextLine();
- for(int j=0;j<fc;j++){
- m2[i][j] = (int)(row.charAt(j) );
- }
- }
- outLoop:
- for(int i=0;i<sr;i++){
- for(int j=0;j<sc;j++){
- if(m1[i][j]==m2[0][0]){
- if(isMatrix(m1,m2,fr,fc,i,j) ){
- found = true;
- break outLoop;
- } else{
- found = false;
- }
- }
- }
- }
- String r = (found==true)?"YES":"NO";
- System.out.println(r);
- steps--;
- }
- }
- public static boolean isMatrix(int[][] m1, int[][] m2, int fr, int fc, int i, int j){
- boolean found = true;
- for(int a=0;a<fr;a++){
- for(int b=0;b<fc;b++){
- try{
- if(m2[a][b]!=m1[i+a][j+b]){
- return false;
- }
- }
- catch(Exception e){
- return false;
- }
- }
- }
- return true;
- }
- }
Comments
Post a Comment