Word Search(Medium)
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.
For example, Given board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
解题思路1:回溯+DFS
复杂度
时间 O() 空间 O(mn)
对矩阵里每个点都进行一次深度优先搜索,看它能够产生一个路径和所给的字符串是一样的。
public boolean exist(char[][] board, String word) {
if(word==null || word.length()==0)
return true;
if (board == null || board.length == 0 || board[0].length == 0)
return false;
boolean[][] visited = 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(helper(board,word,visited,i,j,0))
return true;
}
return false;
}
private boolean helper(char[][] board, String word,boolean[][] visited,int row,int col,int index) {
if(row < 0 || row >= board.length
|| col <0 || col>=board[0].length) {
return false;
}
if(!visited[row][col] && word.charAt(index) == board[row][col]) {
if(index == word.length()-1)
return true;
visited[row][col] = true;
boolean up = helper(board,word,visited,row-1,col,index+1);
boolean down = helper(board,word,visited,row+1,col,index+1);
boolean left = helper(board,word,visited,row,col-1,index+1);
boolean right = helper(board,word,visited,row,col+1,index+1);
visited[row][col] = false;//backtracking
return up || down || left || right;
}
return false;
}