地址:https://leetcode.com/problems/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.
Example:
理解:
想了想应该是从每个位置开始,依次比较字符是否相等,是的话再比较上下左右。
实现:
由于不能重复使用一个cell,因此需要在向后判断的时候把已判断的位置改掉,由于别的位置还需要从头开始判断,因此需要在返回的时候把改掉的改回来。
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if (word.empty() || board.empty() || board[0].empty()) return false;
for(int i=0;i<board.size();++i)
for (int j = 0; j < board[0].size(); ++j) {
if (found(board, word, 0, i, j))
return true;
}
return false;
}
private:
bool found(vector<vector<char>>& board, const string& word, string::size_type pos, int row, int col) {
if (row < 0 || col < 0 || row >= board.size() || col >= board[0].size() || word[pos] != board[row][col]) return false;
if (pos == word.length() - 1) return true;
char tmp = board[row][col];
board[row][col] = '\0';
if (found(board, word, pos + 1, row - 1, col) || found(board, word, pos + 1, row + 1, col) || found(board, word, pos + 1, row, col - 1) || found(board, word, pos + 1, row, col + 1))
return true;
board[row][col] = tmp;
return false;
}
};