方法1—回溯
很简单的回溯题
c++代码
class Solution {
public:
int flag;
vector<vector<char>> vocab;
vector<vector<int>> vv;
void dfs(int i, int j, int bottom, int right, string word, int idx){
if(idx == word.size()){
flag = 1;
return;
}
if(i < 0 || i > bottom || j < 0 || j > right) return;
if(flag==1) return;
if(j < right && vv[i][j+1] == 0 && vocab[i][j+1] == word[idx]){
vv[i][j+1] = 1;
dfs(i, j+1, bottom, right, word, idx+1);
vv[i][j+1] = 0;
}
if(flag==1) return;
if(j > 0 && vv[i][j-1] == 0 && vocab[i][j-1] == word[idx]){
vv[i][j-1] = 1;
dfs(i, j-1, bottom, right, word, idx+1);
vv[i][j-1] = 0;
}
if(flag==1) return;
if(i > 0 && vv[i-1][j] == 0 && vocab[i-1][j] == word[idx]){
vv[i-1][j] = 1;
dfs(i-1, j, bottom, right, word, idx+1);
vv[i-1][j] = 0;
}
if(flag==1) return;
if(i < bottom && vv[i+1][j] == 0 && vocab[i+1][j] == word[idx]){
vv[i+1][j] = 1;
dfs(i+1, j, bottom, right, word, idx+1);
vv[i+1][j] = 0;
}
}
bool exist(vector<vector<char>>& board, string word) {
vocab = board;
flag = 0;
int raw = board.size(), column = board[0].size();
vector<int> v(column, 0);
for(int i=0; i<raw; i++) vv.push_back(v);
for(int i=0; i<raw; i++){
for(int j=0; j<column; j++){
if(board[i][j] == word[0]){
vv[i][j] = 1;
// 当前元素的行、列,board的下边界、右边界,单词及索引
dfs(i, j, raw-1, column-1, word, 1);
vv[i][j] = 0;
}
if(flag) return true;
}
}
return false;
}
};
java代码
class Solution {
private boolean[][] marked;
private int[][] direction = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
private int raw, column; //board的行,列
private char[][] board;
private String word;
boolean inArea(int i, int j){
if(i >= 0 && i < raw && j >= 0 && j < column)
return true;
return false;
}
boolean dfs(int i, int j, int idx){
if(idx == word.length()-1)
return board[i][j] == word.charAt(idx);
if(board[i][j] == word.charAt(idx)){
marked[i][j] = true;
for(int k=0; k<4; k++){
int new_x = i + direction[k][0];
int new_y = j + direction[k][1];
if(inArea(new_x, new_y) && !marked[new_x][new_y]){
if(dfs(new_x, new_y, idx+1)) return true;
}
}
marked[i][j] = false;
}
return false;
}
public boolean exist(char[][] board, String word) {
this.word = word;
this.board = board;
raw = board.length;
column = board[0].length;
marked = new boolean[raw][column];
for(int i=0; i<raw; i++){
for(int j=0; j<column; j++){
if(dfs(i, j, 0)) return true;
}
}
return false;
}
}