leetcode第79题单词搜索
思路:
这就是很典型的回溯问题,我先匹配第一个字符,如果第一个字符匹配到了,我就从这个字符所在位置的上下左右位置寻找下一个字符,一点一点的回溯,通过一个外置的direction来控制我要找的方向,通过剪枝来提高代码的效率
class Solution3 {
private boolean[][] used;
private int row, col;
private char[][] board;
private char[] ws;
private int[][] direction = new int[][] {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
public boolean exist(char[][] board, String word) {
this.row = board.length;
this.col = board[0].length;
this.used = new boolean[row][col];
for (boolean[] u : used) {
Arrays.fill(u, false);
}
this.board = board;
this.ws = word.toCharArray();
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (board[i][j] == ws[0]) {
used[i][j] = true;
if (dfs(i, j, 1)) {
return true;
} else {
used[i][j] = false;
}
}
}
}
return false;
}
private boolean dfs(int i, int j, int depth) {
if (depth == ws.length) {
return true;
}
for (int[] d : direction) {
int newX = i + d[0];
int newY = j + d[1];
// 剪枝
if (!inArea(newX, newY)) {
continue;
}
// 剪枝
if (used[newX][newY]) {
continue;
}
// 剪枝
if (board[newX][newY] != ws[depth]) {
continue;
}
used[newX][newY] = true;
if (dfs(newX, newY, depth + 1)) {
return true;
} else {
used[newX][newY] = false;
}
}
return false;
}
private boolean inArea(int x, int y) {
return x >= 0 && x < this.row && y >= 0 && y < this.col;
}
}
class Solution {
private boolean[][] used;
private int row, col;
private char[][] board;
private char[] ws;
//终于明白这个东西是做什么的了,就是判断上下左右是不是我要找的那个数,真的是搞事情了
private int[][] direction = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
public boolean exist(char[][] board, String word) {
//这种回溯,其实并不是很简单
this.ws = word.toCharArray();
this.board = board;
this.row = board.length;
this.col = board[0].length;
this.used = new boolean[board.length][board[0].length];
for (boolean[] u : used) {
Arrays.fill(u, false);
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (board[i][j] == ws[0]) {
used[i][j] = true;
if (backTrack(i,j,1)){
return true;
}else{
used[i][j] = false;
}
}
}
}
return false;
}
public boolean backTrack(int i, int j, int depth) {
if (depth == ws.length) {
return true;
}
for (int k = 0; k < 4; k++) {
int newI = i + direction[k][0];
int newJ = j + direction[k][1];
//判断是否在表格里面
if (!inArea(newI, newJ)) {
continue;
}
if (used[newI][newJ]) {
continue;
}
if (board[newI][newJ] != ws[depth]) {
continue;
}
used[newI][newJ] = true;
if(backTrack(newI,newJ,depth++)){
return true;
}else{
used[newI][newJ] = false;
}
}
return false;
}
public boolean inArea(int i, int j) {
return i >= 0 && i < this.row && j >= 0 && j < this.col;
}
}