79 Word Search
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
Example 2:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true
Example 3:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false
使用递归求解,深度优先遍历,当某个字母相同时,尝试上下左右四个方向递归下一个字母。
class Solution {
public boolean exist(char[][] board, String word) {
boolean[][] visited=new boolean[board.length][board[0].length];
char first=word.charAt(0);
for(int i=0;i<board.length;++i){
for(int j=0;j<board[0].length;++j){
if(recur(board,word,0,i,j,visited)) return true;
}
}
return false;
}
private boolean recur(char[][] board, String word, int index,
int i, int j, boolean[][]visited){
if(word.charAt(index)!=board[i][j]) return false;
if(index+1==word.length()) return true;
visited[i][j]=true;
if(i-1>=0 && !visited[i-1][j] && recur(board,word,index+1,i-1,j,visited)) return true;
if(i+1<board.length && !visited[i+1][j] && recur(board,word,index+1,i+1,j,visited)) return true;
if(j-1>=0 && !visited[i][j-1] && recur(board,word,index+1,i,j-1,visited)) return true;
if(j+1<board[i].length && !visited[i][j+1] && recur(board,word,index+1,i,j+1,visited)) return true;
visited[i][j]=false;
return false;
}
}