您的位置:首页 > 其它

leetcode 79. Word Search 改进版本的dfs算法

2017-03-07 11:19 417 查看
leetcode 79. Word Search

board[i][j] = '#';采用这种方式进行标记,good idea!
public class Solution {
public static void main(String[] args){
char[][] board = {{'A','B','C','E'},{'S','F','E','S'},{'A','D','E','E'}};
Solution s = new Solution();
s.exist(board, "ABCESEEEFS");
}

public boolean exist(char[][] board, String word) {
char start = word.charAt(0);
int m = board.length;
if(m==0) return false;
int n = board[0].length;
//int[][] used = new int[m]
;

boolean res = false;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
boolean tmp = dfs(board,word,start,m,n,0,i,j);
if(tmp) return true;
}
}
return res;
}

public boolean dfs(char[][] board, String word,char start,int m,int n,int idx,int i,int j){
if(start!=board[i][j]) return false;
if(idx==word.length()-1) return true; // the last char in a word.
board[i][j] = '#';
idx++;
char next = word.charAt(idx);
boolean res = false;
if(i>0) res = res||dfs(board,word,next,m,n,idx,i-1,j);
if(j>0) res = res||dfs(board,word,next,m,n,idx,i,j-1);
if(i+1<m) res = res||dfs(board,word,next,m,n,idx,i+1,j);
if(j+1<n) res = res||dfs(board,word,next,m,n,idx,i,j+1);
board[i][j] = start;
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: