题目链接
法一(回溯法)
public class Solution79 {
private boolean find;
public Solution79() {
this.find = false;
}
private void backtracking(int row, int col, char[][] board, String word, boolean[][] visited, int index) {
if (row < 0 || col < 0 || row >= board.length || col >= board[0].length
|| visited[row][col] || find || board[row][col] != word.charAt(index)) {
return;
}
if (index == word.length() - 1) {
find = true;
return;
}
visited[row][col] = true;
backtracking(row + 1, col, board, word, visited, index + 1);
backtracking(row, col + 1, board, word, visited, index + 1);
backtracking(row - 1, col, board, word, visited, index + 1);
backtracking(row, col - 1, board, word, visited, index + 1);
visited[row][col] = false;
}
public boolean exist(char[][] board, String word) {
if (board == null) {
return false;
}
int rowSize = board.length, colSize = board[0].length;
boolean[][] visited = new boolean[rowSize][colSize];
for (int row = 0; row < rowSize; row++) {
for (int col = 0; col < colSize; col++) {
backtracking(row, col, board, word, visited, 0);
}
}
return find;
}
}
本地测试
lay.showTitle(79);
Solution79 sol79 = new Solution79();
char[][] board79 = new char[][]{{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}};
String word79 = "ABCCED";
arrayOpt.showCharTwoDimArray(board79, board79.length);
System.out.println(word79);
System.out.println(sol79.exist(board79, word79));