[LeetCode] Word Search

来源:互联网 发布:上古世纪人物捏脸数据 编辑:程序博客网 时间:2024/06/07 09:33
[Problem]

Given a 2D board and a word, find if the word exists in thegrid.

The word can be constructed from letters of sequentiallyadjacent cell, where "adjacent" cells are those horizontally orvertically neighboring. The same letter cell may not be used morethan once.

For example,
Given board =

[  ["ABCE"],  ["SFCS"],  ["ADEE"]]
word = "ABCCED", -> returnstrue,
word = "SEE", -> returnstrue,
word = "ABCB", -> returnsfalse.

[Analysis]
深度优先搜索

[Solution]

class Solution {
public:
// DFS
bool DFS(vector<vector<char> > &board, int i, int j, int m, int n, string word, vector<vector<bool> > &visited){
if(word.length() == 0){
return true;
}
else if(i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[0] || visited[i][j] == true){
return false;
}
else{
visited[i][j] = true;

// visit upper
bool upper = DFS(board, i-1, j, m, n, word.substr(1, word.length()-1), visited);
if(upper){
return true;
}

// visit down
bool down = DFS(board, i+1, j, m, n, word.substr(1, word.length()-1), visited);
if(down){
return true;
}

// visit left
bool left = DFS(board, i, j-1, m, n, word.substr(1, word.length()-1), visited);
if(left){
return true;
}

// visit right
bool right = DFS(board, i, j+1, m, n, word.substr(1, word.length()-1), visited);
if(right){
return true;
}

visited[i][j] = false;
}

return false;
}

// exist
bool exist(vector<vector<char> > &board, string word) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

// empty string
if(word.length() == 0){
return true;
}

// get number of rows
int m = board.size();
if(m == 0){
return false;
}

// get number of columns
int n = board[0].size();

// create visited
vector<vector<bool> > visited;
for(int x = 0; x < m; ++x){
vector<bool> row;
for(int y = 0; y < n; ++y){
row.push_back(false);
}
visited.push_back(row);
}

// DFS
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(board[i][j] == word[0]){
// DFS
bool contain = DFS(board, i, j, m, n, word, visited);
if(contain){
return true;
}
}
}
}
return false;
}
};


 说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击