C++:
class Solution {
public:
vector<vector<int>> direc;
vector<vector<bool>> visited;
vector<vector<char>> board;
string word;
int n, m, wlen;
bool DFS(int i, int j, int start)
{
if(start == wlen-1)
{
return board[i][j] == word[start];
}
if(word[start] == board[i][j])
{
visited[i][j] = false;
for(int k = 0; k < 4; k++)
{
int x = i+direc[k][0];
int y = j+direc[k][1];
if(x >= 0 && x < m && y >= 0 && y < n && visited[x][y])
{
if(DFS(x, y, start+1))
return true;
}
}
visited[i][j] = true;
}
return false;
}
bool exist(vector<vector<char>>& board, string word) {
this->board = board;
this->word = word;
m = board.size();
n = board[0].size();
wlen = word.size();
vector<vector<bool>> v(m, vector<bool>(n, true));
this->visited = v;
direc = {{-1, 0}, {0, -1}, {0,1}, {1, 0}};
bool ans = false;
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(word[0] == board[i][j])
{
ans = DFS(i, j, 0);
if(ans == true) return true;
}
}
}
return ans;
}
};
提交完成后发现目前榜一的代码尽管也是用深搜但是执行效率是真的高,放在下面:
class Solution {
public:
bool exist(vector<vector<char>>& board, const string& word) {
//cout << board.size() << "*" << board[0].size() << " , " << word.size() << endl;
rows = board.size();
cols = board[0].size();
for (int row = 0; row < rows; ++row)
{
for (int col = 0; col < cols; ++col) {
if (dfs(board, word, row, col, 0))
return true;
}
}
return false;
}
private:
int rows;
int cols;
bool dfs(vector<vector<char>>& board, const string& word, int r, int c, int k)
{
if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] != word[k])
return false;
if (k == word.size()-1)
return true;
board[r][c] = '\0';
bool res = dfs(board, word, r-1, c, k+1) || dfs(board, word, r+1, c, k+1)
|| dfs(board, word, r, c-1, k+1) || dfs(board, word, r, c+1, k+1);
board[r][c] = word[k];
// if(res)
// cout << board[r][c] << endl;
return res;
}
};