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 .
Test instructions: In a matrix, adjacent elements can be the top, bottom, left, and right elements. It is also required that the same character in the matrix cannot be matched repeatedly.
Idea: Use the DFS traversal matrix until the string is traversed, indicating a match. However, you need to record which characters in the matrix are already matched.
Because the English character range is 0~127, after traversing a character, the c^=128 operation is performed, and the character is not repeated in subsequent matches
Match to, thereby achieving the effect of the tag. The marked characters need to be restored when backtracking.
The code is as follows:
Public BooleanExistChar[] board, String word) { for(inti=0; i<board.length; i++) { for(intj=0; j<board[0].length; J + +) { if(Exist (board, I, J, Word, 0)) return true; } } return false; } Public BooleanExistChar[] board,intXintY, String Word,intindex) { if(Index = = Word.length ())return true; if(X < 0 | | y<0 | | x>=board.length | | y>=board[0].length | | board[x][y]! =Word.charat (index))return false; Board[x][y]^= 128; Booleanexist = exist (board, x-1, y, Word, index+1) | |exist (board, X+1, y, Word, index+1) | |exist (board, X, y-1, Word, index+1) | |exist (board, X, y+1, Word, index+1) ; Board[x][y]^= 128; returnexist; }
LeetCode-79 Word Search