您的位置:首页 > 其它

10.11 Word Search

2014-07-29 08:34 295 查看
Link: http://blog.csdn.net/linhuanmars/article/details/24336987

My original code:

public class Solution {
public boolean exist(char[][] board, String word) {
if(board == null) return false;
if(word == null) return true;
return helper(board, word, 0, 0, 0);
}

public boolean helper(char[][] board, String word, int start, int row, int col){
if(start == word.length()){
return true;
}
if(board[row][col] == word.charAt(start)){
if(row < board.length-1){
return helper(board, word, start+1, row+1, col);
}
if(col < board[0].length-1){
return helper(board, word, start+1, row, col+1);
}
}
return true;
}
}


The thought is ok, but the code is not correct. 

Correct:

TIme: for loop: O(m*n), search: O(n*n) since DFS = O(E+V) = O(m*n). In a m*n graph, there are (n-1)*m + (m-1)*n edges.(see the Figure)



So total time complexity = O(m^2*n^2). Space: O(mn).

public class Solution {
public boolean exist(char[][] board, String word) {
int m = board.length;
int n = board[0].length;
boolean[][] visited = new boolean[m]
;
//we can start from any cell on the board
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(search (board, word, 0, i, j, visited)){//if we can find a valid path, return T
return true;
}
}
}
return false;//If no path exists, return false
}

public boolean search(char[][] board, String word, int index, int row, int col, boolean[][] visited){
if(index == word.length()){
return true;
}
if(row<0 || col <0 || row >= board.length || col >= board[0].length)return false;
if(visited[row][col]) return false;
if(board[row][col] != word.charAt(index)) return false;
visited[row][col] = true;
boolean res = search (board, word, index+1, row-1, col, visited) ||//上
search (board, word, index+1, row+1, col, visited) ||//下
search (board, word, index+1, row, col-1, visited)||//左
search (board, word, index+1, row, col+1, visited);//右
visited[row][col] = false;//backtrack
return res;
}
}


Note: Each time before we start from a new cell and call search, we set the flag back to false. Since each new path can use previous nodes.  
visited[row][col] = false;//backtrack

相关题目:There is a similar (Top, Bottom, Left, Right) question (on CC150?) 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: