<a target=_blank href="https://oj.leetcode.com/problems/word-search/">
</a>
https://oj.leetcode.com/problems/word-search/
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 =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
这题是深度优先搜索,但是在进入下一步之前会把当前格标记为‘.’,避免重复使用。
一次搜索的复杂度是O(E+V),E是边的数量,V是顶点数量,在这个问题中他们都是O(m*n)量级的(因为一个顶点有固定上下左右四条边)。加上我们对每个顶点都要做一次搜索,所以总的时间复杂度最坏是O(m^2*n^2)
空间复杂度是递归过程中产生的,大约是O(4*word.length())
public class Solution {
public boolean exist(char[][] board, String word) {
if(word==null || word.length()==0) return true;
if(board==null || board.length==0) return false;
for(int i=0; i<board.length; i++){
for(int j=0; j<board[0].length; j++){
boolean ret = helper(board, word, 0, i, j);
if(ret==true) return true;
}
}
return false;
}
public boolean helper(char[][]board, String word, int index, int x, int y){
if(index==word.length()) return true;
if(x<0||x>=board.length||y<0||y>=board[0].length||board[x][y]!=word.charAt(index)) return false;
char c = board[x][y];
board[x][y] = '.';
boolean ret = helper(board, word, index+1, x-1, y)||
helper(board, word, index+1, x+1, y)||
helper(board, word, index+1, x, y-1)||
helper(board, word, index+1, x, y+1);
board[x][y] = c;
return ret;
}
}