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 =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
public class Solution { public boolean exist(char[][] board, String word) { // Start typing your Java solution below // DO NOT write main() function if(word.length() == 0)return true; int h = board.length; if(h == 0) return false; int w = board[0].length; boolean[][] flag = new boolean[h][w]; for(int i = 0 ; i < h; i++){ for(int j = 0 ; j < w ; j++){ if(word.charAt(0) == board[i][j]){ if(func(board,word,0,h,w,i,j,flag)) return true; } } } return false; } public boolean func(char[][] board, String word, int level, int h, int w, int x,int y, boolean[][] flag){ if(level == word.length())return true; if(x < 0 || x >= h || y < 0 || y >= w) return false; if(flag[x][y]||board[x][y] != word.charAt(level)) return false; flag[x][y] = true; if(func(board,word,level+1,h,w,x,y-1,flag))//up return true; if(func(board,word,level+1,h,w,x,y+1,flag))//down return true; if(func(board,word,level+1,h,w,x-1,y,flag))//left return true; if(func(board,word,level+1,h,w,x+1,y,flag)) return true; flag[x][y] = false;// missing here otherwise only goes one loop return false; } }