题目
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]
给定 word = “ABCCED”, 返回 true
给定 word = “SEE”, 返回 true
给定 word = “ABCB”, 返回 false
分析
核心思想:
1.首先根据题目以及遍历方法可以知道用dfs。需要定义一个pos以及一个use。pos是确认查找完成。use是因为
深度遍历,需要确认哪些之前遍历过,防止重复遍历。
2.dfs函数中需要注意的是遍历传入坐标的上下左右点,成功继续往下,否则返回。同时需要注意边界条件,
因为这个会涉及到数组的具体元素。所以要防止增加或者减少的时候越界,所以需要将边界条件放在
最前面进行判断
下面这个做法是自己的做法,但是时间和内存消耗都比较大,因为形参列表中多了一个二维数组vector,即使是引用,
所以一般不要在形参列表加太多的参数。哪怕是定义全局变量。
bool dfs(int pos, int x, int y, vector<vector<int>>& tmp, vector<vector<char>>& board, string word){
if (pos == word.size()){
return true;
}
vector<vector<int>> path = { { 0, 1 }, { 0, -1 }, { 1, 0 }, {-1,0} };
for (int i = 0; i < path.size(); ++i){
int dx = x + path[i][0];
int dy = y + path[i][1];
if (dx >= 0 && dx < board.size() && dy >= 0 && dy < board[0].size() && !tmp[dx][dy] && board[dx][dy] == word[pos]){
tmp[dx][dy] = 1;
if (dfs(pos + 1, dx, dy , tmp, board, word)){
return true;
}
tmp[dx][dy] = 0;
}
}
return false;
}
bool exist(vector<vector<char>>& board, string word) {
if (word.empty()){
return false;
}
int row = board.size();
int col = board[0].size();
vector<vector<int>> tmp(row, vector<int>(col, 0));
for (int i = 0; i < row; ++i){
for (int j = 0; j < col; ++j){
if (board[i][j] == word[0]){
tmp[i][j] = 1;
if (dfs(1, i, j,tmp, board, word)){
return true;
}
tmp[i][j] = 0;
}
}
}
return false;
}
下面这种做法是看到别人优化的做法
class MyClass
{
public:
int m, n;
vector<vector<int>> use;
int dir[4][2] = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } };
bool dfs(int pos, int x, int y, vector<vector<char>> &board, string& word){
int i, j;
if (pos == word.length()) return true;
else{
int newx, newy;
for (int i = 0; i<4; i++){
newx = x + dir[i][0];
newy = y + dir[i][1];
if (newx >= 0 && newx<m && newy >= 0 && newy<n && !use[newx][newy] && board[newx][newy] == word[now]){
use[newx][newy] = 1;
if (dfs(pos + 1, newx, newy, board, word)) return true;
use[newx][newy] = 0;
}
}
}
return false;
}
bool exist(vector<vector<char>>& board, string word) {
m = board.size(), n = board[0].size();
use = vector<vector<int>>(m, vector<int>(n, 0));
for (int i = 0; i<m; i++){
for (int j = 0; j<n; j++){
if (board[i][j] == word[0]){
use[i][j] = 1;
if (dfs(1, i, j, board, word)) return true;
use[i][j] = 0;
}
}
}
return false;
};