You are given a 2D array of characters and a character pattern. WAP to find if pattern is present in 2D array. Pattern can be in any way (all 8 neighbors to be considered) but you can’t use same character twice while matching. Return 1 if match is found, 0 if not.
Java Program:
public class Matrix {
private static boolean[][] visited;
private char[][] grid = {{'a','i','b'},
{'m','b','c'},
{'g','r','i'},
{'o','o','t'},
{'s','f','m'}};
private String searchString = "microsoft";
public static void main(String[] args) {
Matrix gridObject = new Matrix();
gridObject.initialize(gridObject.grid.length, gridObject.grid[0].length);
boolean result = false;
for (int i = 0; i < gridObject.grid.length; i++) {
for(int j = 0; j < gridObject.grid[i].length; j++) {
result = gridObject.traverseAndFind(gridObject.grid, i, j, gridObject.searchString, 0);
if(result) {
break;
}
}
if(result) {
break;
}
}
if(result) {
System.out.println("The string is present in the grid");
}
else {
System.out.println("The string is not present in the grid");
}
}
//Function to do all the primary initialization.
public void initialize(int x, int y) {
visited = new boolean[x][y];
}
public boolean traverseAndFind(char[][] inputGrid, int r, int c, String inputString, int index) {
if(index == inputString.length()) {
return true;
}
else if(r >= 0 && r < inputGrid.length && c >= 0 && c < inputGrid[r].length
&& !visited[r][c] && inputGrid[r][c] == inputString.charAt(index)) {
visited[r][c] = true;
return (traverseAndFind(inputGrid, r, c + 1, inputString, index + 1)) ||
traverseAndFind(inputGrid, r + 1, c + 1, inputString, index + 1) ||
traverseAndFind(inputGrid, r + 1, c, inputString, index + 1) ||
traverseAndFind(inputGrid, r + 1, c - 1, inputString, index + 1) ||
traverseAndFind(inputGrid, r, c - 1, inputString, index + 1) ||
traverseAndFind(inputGrid, r - 1, c - 1, inputString, index + 1) ||
traverseAndFind(inputGrid, r - 1, c, inputString, index + 1) ||
traverseAndFind(inputGrid, r - 1, c + 1, inputString, index + 1);
}
else if(r >= 0 && r < inputGrid.length && c >= 0 && c < inputGrid[r].length) {
visited[r][c] = false;
}
return false;
}
}