后来在dfs里面新加了一个参数boolean[][] visited用来记录是否访问过了。这样每次虽然要新建visited数组,但不用拷贝了,但还是TLE。
后来运用我总结的DFS模板,在改变board访问元素之前先保存到一个tmp变量中,在结束递归后还原现场。压线AC!
package Level3;
/**
* 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.
*
*/
public class S79 {
public static void main(String[] args) {
char[][] board = {{'C','A','A'},{'A','A','A'},{'B','C','D'}};
String word = "AAB";
System.out.println(exist(board, word));
}
public static boolean exist(char[][] board, String word) {
// 对每一个节点进行深搜
for(int i=0; i
=0 && board[x-1][y] != '.'){
b1 = dfs(board, word, index+1, x-1, y);
}
if(!b1 && y-1>=0 && board[x][y-1] != '.'){
b2 = dfs(board, word, index+1, x, y-1);
}
if(!b1 && !b2 && x+1