题目描述:
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.
中文理解:
给定一个二维字符数组,任意给定一个word,判断word是否可以由字符数组中的元素邻接组成。
解题思路:
使用回溯的思路,不过同时遍历这个位置的字符的上下左右四个方位,同时使用一个used二维数组来标记该位置是否已被遍历。
代码(java):
class Solution {
public boolean exist(char[][] board, String word) {
if(word.length()==0)return true;
else if(board.length==0)return false;
boolean res=false;
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(board[i][j]==word.charAt(0)){
res=res || existHelper(board,i,j,word,0,new int [board.length][board[0].length]);
}
}
}
return res;
}
public boolean existHelper(char[][] board,int row,int col,String word,int index,int[][] used){
if(row>=board.length || col>=board[0].length ||row<0 || col<0)return false;
boolean res=false;
if(board[row][col]==word.charAt(index) && used[row][col]==0){
used[row][col]=1;
if(index==word.length()-1)return true;
else res= existHelper(board,row-1,col,word,index+1,used) || existHelper(board,row+1,col,word,index+1,used)
|| existHelper(board,row,col-1,word,index+1,used) || existHelper(board,row,col+1,word,index+1,used);
used[row][col]=0;
}
return res;
}
}