Skip to content

Instantly share code, notes, and snippets.

@sdpatil
Created August 13, 2017 21:52
Show Gist options
  • Save sdpatil/0334e90696db9bc85935bc65283dc0d5 to your computer and use it in GitHub Desktop.
Save sdpatil/0334e90696db9bc85935bc65283dc0d5 to your computer and use it in GitHub Desktop.
Search for a sequence in 2D array
import java.util.List;
/**
* Problem: Write a program that takes as argument a 2D array and a 1D array and checks whether the
* 1D array occurs in 2D array
*/
public class SearchSequenceIn2DArray {
static class Attempt {
int x;
int y;
int offset;
public Attempt(int x, int y, int offset) {
this.x = x;
this.y = y;
this.offset = offset;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IsPatternContainedInGrid.Attempt attempt = (IsPatternContainedInGrid.Attempt) o;
if (x != attempt.x) return false;
if (y != attempt.y) return false;
return offset == attempt.offset;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
result = 31 * result + offset;
return result;
}
}
/*
This method tries with every cell as starting position in the 2D array to check if that is the
starting point for the pattern
*/
public boolean isPatternContainedInGrid(List<List<Integer>> grid,
List<Integer> pattern){
for(int row = 0 ; row < grid.size() ; row++){
for(int column = 0 ; column < grid.get(0).size() ; column++){
if(isPatternContainedInGrid(grid,pattern,row,column,0))
return true;
}
}
return false;
}
/*
This method searches for rest of the offset to match at given position
*/
public boolean isPatternContainedInGrid(List<List<Integer>> grid,
List<Integer> pattern, int row, int column, int offset){
if(offset == pattern.size())
return true;
if (isFeasible(grid,row,column)) {
if (grid.get(row).get(column) == pattern.get(offset)) {
if (isPatternContainedInGrid(grid, pattern, row - 1, column, offset + 1) ||
isPatternContainedInGrid(grid, pattern, row + 1, column, offset + 1) ||
isPatternContainedInGrid(grid, pattern, row, column - 1, offset + 1) ||
isPatternContainedInGrid(grid, pattern, row, column + 1, offset + 1))
return true;
}
}
return false;
}
public boolean isFeasible(List<List<Integer>> grid, int row, int column){
if(row >=0 && column >=0 && row < grid.size() && column < grid.get(0).size())
return true;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment