Word search by LeetCode
java编写
public class word_search {
static boolean xx;
public static void main(String[] args) {
char[][] a = {{‘A’,‘B’,‘C’,‘E’},
{‘S’,‘F’,‘C’,‘S’},
{‘A’,‘D’,‘E’,‘E’}};
System.out.println(exist(a,“ABC”));
}
public static boolean exist(char[][] board, String word) {
boolean[][] pan=new boolean[board.length][board[0].length];
for(int i=0;i<board.length;i++)
for(int j=0;j<board[0].length;j++) {
pan[i][j]=true;
String s = “”+board[i][j];
dfs(board, word, pan, 1,s,i,j);
s="";
pan[i][j]=false;
}
return xx;
}
public static void dfs(char[][] board,String word,boolean[][] pan,int num,String com,int i1,int j1) {
if(numword.length()&&com.equals(word)) {
System.out.println(com);
xx=true;
}
for(int i=0;i<board.length;i++)
for(int j=0;j<board[0].length;j++) {
if(pan[i][j]false&&((i+1i1&&jj1)||(i-1i1&&jj1)||(ii1&&j-1j1)||(ii1&&j+1j1))) {
com+=""+board[i][j];
pan[i][j]=true;
dfs(board, word, pan, num+1, com,i, j);
pan[i][j]=false;
com=com.substring(0, com.length()-1);
}else {
continue;
}
}
}
}
难受啊马飞飞,现在凡是用到回溯的方法,我都会超时,但我确实想不到其他好的方法,所以我一直会往回溯递归这个方向去想,然后就一直陷在里面出不来,是真的难受,每当看到自己写一堆代码,但是看别人的答案是灰长短,然后就感觉自己很笨,虽然是真的笨(~ ̄(OO) ̄)ブ。下面为快的答案。
class Solution {
public boolean exist(char[][] board, String word) {
boolean result;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == word.charAt(0)) {
result = dsf(board, word, i, j, 0);
if (result) {
return true;
}
}
}
}
return false;
}
private static boolean dsf(char[][] board, String word, int i, int j, int index) {
if (index == word.length()) {
return true;
}
if (i < 0 || i >= board.length || j < 0 || j >= board[i].length) {
return false;
}
if (board[i][j] != word.charAt(index)){
return false;
}
boolean result;
board[i][j] += 60;
result = dsf(board, word, i - 1, j, index + 1)
|| dsf(board, word, i + 1, j, index + 1)
|| dsf(board, word, i, j - 1, index + 1)
|| dsf(board, word, i, j + 1, index + 1);
board[i][j] -= 60;
return result;
}
}
8说了,人家也用了dfs回溯,就我自己写的超时了。嘿嘿,就是自己辣鸡,还是那句话,继续加油。