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 is those horizontally or V Ertically neighboring. The same letter cell is used more than once.
For example,
Given Board =
[ ["ABCE"], ["SFCs"], ["Adee"]]
Word = "ABCCED"
, returns true
,
Word = "SEE"
, returns true
,
Word = "ABCB"
, returns false
.
Problem Solving Ideas:
Open an array to save the data for access, using DFS, Java implementation is as follows:
Static public Boolean exist (char[][] board, String Word) {if (Board.length = = 0 | | board[0].length = = 0 | | word.length () = = 0) return false;boolean[][] isused=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 (board[i][j] = = Word.charat (0)) {is Used[i][j]=true;if (Dfs (board,word,i,j,0,isused)) return true;isused[i][j]=false;} return false;} public static Boolean DFS (char[][] board,string word,int i,int j,int depth,boolean[][] isused) {if (Depth==word.length ()- 1) Return true;if (I>=1&&board[i-1][j]==word.charat (depth+1) &&!isused[i-1][j]) {isUsed[i-1][j]= True;if (Dfs (board,word,i-1,j,depth+1,isused)) return true;isused[i-1][j]=false;} if (I<=board.length-2&&board[i+1][j]==word.charat (depth+1) &&!isused[i+1][j]) {isUsed[i+1][j]= True;if (Dfs (board,word,i+1,j,depth+1,isused)) return true;isused[i+1][j]=false;} if (J>=1&&board[i][j-1]==word.charat (depth+1) &&!isused[i][j-1]& &!isused[i][j-1]) {isused[i][j-1]=true;if (Dfs (board,word,i,j-1,depth+1,isused)) return true;isused[i][j-1]= false;} if (J<=board[0].length-2&&board[i][j+1]==word.charat (depth+1) &&!isused[i][j+1]) {isUsed[i][j+ 1]=true;if (Dfs (board,word,i,j+1,depth+1,isused)) return true;isused[i][j+1]=false;} return false;}
Java for Leetcode 079 Word Search