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.
http://www.lintcode.com/en/problem/word-search/
Discussion
从board上任一点开始DFS,直到找到word。状态转移的时候是上下左右四个方向作为当前点的neighbors。
Solution
// Time: O(m * n * l), l is length of the word
// Space: O(l)
class Solution {
public:
/**
* @param board: A list of lists of character
* @param word: A string
* @return: A boolean
*/
bool exist(vector<vector<char> > &board, string word) {
int m = board.size();
if(m == 0) return false;
int n = board[0].size();
vector<vector<bool> > visited(m, vector<bool>(n, false));
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
if(dfs(board, i, j, word, 0, visited)) {
return true;
}
}
}
return false;
}
bool dfs(vector<vector<char>> &board, int i, int j, string word, int pos,
vector<vector<bool>> &visited) {
if(pos == word.length()) return true;//found word
//invalid position
int m = board.size();
int n = board[0].size();
if(i<0 || i>=m || j<0 || j>=n)
return false;
//visited or not equal
if(word[pos] != board[i][j] || visited[i][j]) {
return false;
}
visited[i][j] = true;
if(dfs(board, i+1, j, word, pos+1, visited) || dfs(board, i-1, j, word, pos+1, visited)
||dfs(board, i, j+1, word, pos+1, visited) || dfs(board, i, j-1, word, pos+1, visited)) {
return true;
}
visited[i][j] = false;
return false;
}
};