链接:http://leetcode.com/onlinejudge#question_79
原题:
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搜索,按四个方向走,不断回溯
const int Solution::dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
代码:
class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (word.size()==0)
return true;
if (board.size()==0)
return false;
int rows = board.size();
int cols = board[0].size();
vector<vector<bool> > used;
for (int i=0; i<rows; i++)
used.push_back(vector<bool>(cols));
for (int i=0; i<rows; i++) {
for (int j=0; j<cols; j++) {
if (word[0]==board[i][j]) {
used[i][j] = true;
if (dfs(board, used, word, 1, i, j))
return true;
used[i][j] = false;
}
}
}
return false;
}
private:
static const int dir[4][2];
bool dfs(const vector<vector<char> > &board, vector<vector<bool> > &used,
const string &word, int n, int x, int y) {
if (n==word.size())
return true;
int rows = board.size();
int cols = board[0].size();
for (int i=0; i<4; i++) {
int nx = x + dir[i][0];
int ny = y + dir[i][1];
if (nx>=0 && nx<rows && ny>=0 && ny<cols) {
if (!used[nx][ny] && word[n]==board[nx][ny]) {
used[nx][ny] = true;
if (dfs(board, used, word, n+1, nx, ny))
return true;
used[nx][ny] = false;
}
}
}
return false;
}
};
const int Solution::dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};