Word Search
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.
思路:
题目没什么特别的难度,就是做一个深搜即可。
题解:
class Solution {
public:
typedef vector<vector<char>> board_t;
int N, M;
board_t used_mark;
bool navigate(const board_t& board, const string& word,
int board_i, int board_j, int word_offset)
{
if (board_i < 0 || board_j < 0 ||
board_i >= N || board_j >= M ||
used_mark[board_i][board_j] != 0 ||
board[board_i][board_j] != word[word_offset])
return false;
if (word_offset == word.size() - 1)
return true;
used_mark[board_i][board_j] = 1;
if ( navigate(board, word, board_i, board_j - 1, word_offset + 1) ||
navigate(board, word, board_i, board_j + 1, word_offset + 1) ||
navigate(board, word, board_i - 1, board_j , word_offset + 1) ||
navigate(board, word, board_i + 1, board_j , word_offset + 1) )
return true;
used_mark[board_i][board_j] = 0;
return false;
}
bool exist(const board_t& board, const string& word)
{
N = board.size();
M = board[0].size();
used_mark.resize(N);
for (auto & m : used_mark)
{
m.resize(M);
fill(begin(m), end(m), 0);
}
for (auto i = 0; i < N; ++i)
for (auto j = 0; j < M; ++j)
if (board[i][j] == word[0])
if (navigate(board, word, i, j, 0))
return true;
return false;
}
};
本文介绍了一个二维网格中查找指定单词的算法实现。通过深度优先搜索(DFS)的方式遍历网格,寻找与目标单词匹配的路径。文章提供了详细的C++代码示例,并解释了如何避免重复使用同一格子。
984

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



