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:
bool exist(vector<vector<char> > &board, string word) {
if(board.size()<1 || word.size()<1) return false;
int m = board.size();
int n = board[0].size();
for(int i = 0; i < m; ++i) {
for(int j = 0; j < n; ++j) {
vector<vector<char> > tmpBoard = vector<vector<char> >(board);
if(match(tmpBoard, i, j, word, 0)) return true;
}
}
}
bool match(vector<vector<char> > &board, int i, int j, string word, int k) {
if(i < 0 || i >= board.size() || j < 0 || j >= board[0].size()) return false;
if(k < 0 || k > word.size()) return false;
if(board[i][j] == word[k]) {
if(k == word.size()-1) return true;
board[i][j] = '*';
++k;
return
match(board, i+1, j, word, k) ||
match(board, i-1, j, word, k) ||
match(board, i, j+1, word, k) ||
match(board, i, j-1, word, k);
}
return false;
}
};
欢迎关注微信公众号——计算机视觉: