Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example, Given board =
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E']]
word = "ABCCED", -> returns true,word = "SEE", -> returns true,word = "ABCB", -> returns false.
public class Solution { public boolean exist(char[][] board, String word) { boolean[][] flag=new boolean[board.length][board[0].length]; for(int i=0;i<board.length;i++){ for(int j=0;j<board[0].length;j++){ if(def(board, word, i, j, flag)) return true; } } return false; } public boolean def(char[][] board,String target,int i,int j,boolean[][] flag){ if(i<0||i>=board.length||j<0||j>=board[0].length)return false; if(target.charAt(0)!=board[i][j]||flag[i][j])return false; if(target.length()==1)return true; flag[i][j]=true; if(def(board, target.substring(1), i-1, j,flag))return true; if(def(board, target.substring(1), i+1, j,flag))return true; if(def(board, target.substring(1), i, j-1,flag))return true; if(def(board, target.substring(1), i, j+1,flag))return true; flag[i][j]=false; return false; } }
