思想:
DFS
class Solution {
private:
//Word Search
int dir[4][2] = {
{ 0,-1},//left
{ 0, 1},//right
{-1, 0},//top
{ 1, 0},//down
};
const int DIR = 4;
bool rangeOK(vector<vector<char>> &board,int x,int y) {
const size_t m = board.size();
const size_t n = board[0].size();
if(x<0 || x>m-1 || y<0 || y>n-1) return false;
else return true;
}
bool dfs(vector<vector<char>> &board, string word, vector<vector<bool>> &map, int x, int y, int loc) {
if(loc == word.size()) return true;
if(!rangeOK(board, x, y)) return false;
if(map[x][y]) return false;
if(board[x][y] != word[loc]) return false;
map[x][y] = true;
for(int i=0;i<DIR;i++) {
int xx = x + dir[i][0];
int yy = y + dir[i][1];
bool ret = dfs(board, word, map, xx, yy, loc+1);
if(ret == true) return true;
}
map[x][y] = false;
return false;
}
public:
bool exist(vector<vector<char>>& board, string word) {
const size_t m = board.size();
const size_t n = board[0].size();
vector<vector<bool>> map = vector<vector<bool>>(m,vector<bool>(n,false));
for(int i = 0; i < m; ++i) {
for(int j = 0; j < n; ++j) {
if(dfs(board,word,map,i,j,0)) {
return true;
}
}
}
return false;
}
};