您的位置:首页 > 其它

[LeetCode] Word Search

2017-09-10 20:45 155 查看
[Problem]
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
.

[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的博客
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: