Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Q:给定一个字符表,判断某单词是否在表格中出现。表格中的每个字符最多使用一次,下一个字符必须是上一个字符的相邻字符。
Constraints:
- m == board.length
- n = board[i].length
- 1 <= m, n <= 6
- 1 <= word.length <= 15
- board and word consists of only lowercase and uppercase English letters.
Example 1:**Input:** board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
**Output:** true
Example 2:**Input:** board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
**Output:** true
Example 3:**Input:** board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
**Output:** false
方法:深度优先搜索
class Solution {
public:
class Point{
public:
int x; // 行索引
int y; // 列索引
int d; // 方向索引
Point():x(0), y(0), d(0){}
Point(int _x, int _y):x(_x), y(_y), d(0){}
};
bool exist(vector<vector<char>>& board, string word) {
if(word.length() <= 0){
return true;
}
int n = board.size(), m = board[0].size();
stack<Point> path;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
if(board[i][j] == word[0] && dfs(board, word, i, j)){
return true;
}
}
}
return false;
}
bool dfs(vector<vector<char>>& board, string& word, int i, int j){
// 在索引i、j处深度优先搜索,查找word
// 已知 board[i][j] == word[0]
int n = board.size(), m = board[0].size();
int offset[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
stack<Point> path;
vector<vector<bool>> visited(n, vector<bool>(m, false));
path.push(Point(i, j));
visited[i][j] = true;
while(path.size() < word.length()){
Point& cp = path.top();
if(cp.d >= 4){
// cp的四个方向都访问过,都不行,需要退出当前节点,回到上一个节点
visited[cp.x][cp.y] = false;
path.pop();
if(path.empty()){
return false;
}
}
else{
Point np;
np.x = cp.x + offset[cp.d][0];
np.y = cp.y + offset[cp.d][1];
cp.d += 1; // 下次再访问该点时的下一个相邻方向
if(isIn(np, n, m) && !visited[np.x][np.y] && board[np.x][np.y] == word[path.size()]){
// 下一个位置在内部、未访问过、且是下一个要访问的字符
path.push(np);
visited[np.x][np.y] = true;
}
}
}
return true;
}
bool isIn(Point p, int n, int m){
if(p.x >= 0 && p.x < n && p.y >= 0 && p.y < m){
return true;
}
return false;
}
};
运行效率评价:
Success Details
Runtime: 752 ms, faster than 17.20% of C++ online submissions for Word Search.
Memory Usage: 7.8 MB, less than 5.08% of C++ online submissions for Word Search.