Example:
board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]
Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.
做完 NQueen写了下面很傻逼的代码,就TLE,该结束不结束啊。没一个答案会这样是不,不是做程序员的脑子。。。
package DFSTest;
public class WordSearchTest {
public int[][] direc = new int[][]{
{1,0},{0,1},{-1,0},{0,-1}
};
public boolean exist(char[][] board, String word) {
int[][] visited = new int[board.length][board[0].length];
StringBuffer buffer = new StringBuffer();
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
visited[i][j] = 0;
}
}
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
System.out.println("i:" + i + " j:" + j);
if(DFS(board, word, i, j, visited, buffer))
return true;
}
}
return false;
}
public boolean DFS(char[][] board, String word,
int row, int col, int[][] visited, StringBuffer buffer){
buffer.append(board[row][col]);
System.out.println(buffer.toString());
System.out.println("visited:");
for(int i = 0; i < visited.length; i++) {
for(int j = 0; j < visited[0].length; j++)
System.out.print(visited[i][j]);
System.out.println();
}
if(buffer.toString().equals(word))
return true;
for(int i = 0; i < direc.length; i++){
int nextRow = row + direc[i][0];
int nextCol = col + direc[i][1];
visited[row][col] = 1;
System.out.println("next:" + nextRow + "" + nextCol);
if(nextRow >= 0 && nextRow < board.length && nextCol >= 0 && nextCol < board[0].length){
if(visited[nextRow][nextCol] == 1)
continue;
if(DFS(board, word, nextRow, nextCol, visited, buffer))
return true;
}
}
visited[row][col] = 0;
buffer.deleteCharAt(buffer.length() - 1);
return false;
}
public static void main(String[] args) {
WordSearchTest test = new WordSearchTest();
char[][] board = new char[][] {
{'a', 'b'}
};
String str = new String("ba");
if(test.exist(board, str))
System.out.println("存在");;
}
}
下面分享正确代码:
Runtime: 4 ms, faster than 88.57% of Java online submissions for Word Search.
class Solution {
public boolean exist(char[][] board, String word) {
char[] words = word.toCharArray();
int[][] visited = new int[board.length][board[0].length];
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
visited[i][j] = 0;
}
}
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(DFS(board, word, i, j, 0, visited))
return true;
}
}
return false;
}
public boolean DFS(char[][] board,
String word, int i, int j, int n, int[][] visited){
if(i < 0 || i >= board.length || j < 0 || j >=board[0].length || visited[i][j] == 1)
return false;
if(board[i][j] != word.charAt(n))
return false;
if(n == word.length() - 1)
return true;
visited[i][j] = 1;
boolean exist = DFS(board, word, i, j + 1, n + 1, visited)||
DFS(board, word, i, j - 1, n + 1, visited)||
DFS(board, word, i + 1, j, n + 1, visited)||
DFS(board, word, i - 1, j, n + 1, visited);
visited[i][j] = 0;
return exist;
}
}
总结
这个东西吧,只可意会,没办法言传。今天能写出来,明天不一定就犯啥错了,继续多做几遍吧。