Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]word =
"ABCCED",
-> returns true,word =
"SEE",
-> returns true,word = "ABCB",
-> returns false.
解法:DFS
bool exist(vector<vector<char> > &board, string word) {
int m = board.size();
if (m == 0) return false;
int n = board[0].size();
if (n == 0) return false;
if (word.size() == 0) return false;
vector<int> x;
vector<int> y;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (board[i][j] == word[0])
{
x.push_back(i);
y.push_back(j);
}
for (int i = 0; i < x.size(); i++)
{
if (dfs(board, word, 1, x[i], y[i], m, n)) return true;
}
return false;
}
bool dfs(vector<vector<char> > &board, string& word, int index, int x, int y, int m, int n)
{
if (index == word.size()) return true;
char temp = board[x][y];
board[x][y] = '.';
bool res = false;
if (x > 0 && board[x - 1][y] == word[index])
res |= dfs(board, word, index + 1, x - 1, y, m, n);
if (res) return true;
if (x < m - 1 && board[x + 1][y] == word[index])
res |= dfs(board, word, index + 1, x + 1, y, m, n);
if (res) return true;
if (y > 0 && board[x][y - 1] == word[index])
res |= dfs(board, word, index + 1, x, y - 1, m, n);
if (res) return true;
if (y < n - 1 && board[x][y + 1] == word[index])
res |= dfs(board, word, index + 1, x, y + 1, m, n);
if (res) return true;
board[x][y] = temp;
return res;
}
本文介绍了一种使用深度优先搜索(DFS)算法解决在二维网格中查找给定单词的问题。通过遍历网格并检查相邻单元格是否匹配单词字符,实现对单词存在性的判断。
990

被折叠的 条评论
为什么被折叠?



