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.
Example:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
classSolution{privateint R, C;publicbooleanexist(char[][]board,Stringword){ R =board.length; C = board[0].length;for(int r =0; r < R;++r){for(int c =0; c < C;++c){if(board[r][c]==word.charAt(0)){if(dfs(board, word,0, r, c))returntrue;}}}returnfalse;}privatebooleandfs(char[][]board,Stringword,intpos,intr,intc){if(pos ==word.length()-1)returntrue;char curr = board[r][c]; board[r][c]='*';int[] dr =newint[]{0,-1,0,1};int[] dc =newint[]{-1,0,1,0};for(int i =0; i <4;++i){int newR = r + dr[i];int newC = c + dc[i];if(newR <0|| newR >= R || newC <0|| newC >=C|| board[newR][newC]!=word.charAt(pos +1))continue;// 检查是否valid,同时也考虑了去重if(dfs(board, word, pos +1, newR, newC))returntrue;} board[r][c]= curr;returnfalse;}}