leetcode 79.Word Search
阿新 • • 發佈:2018-12-20
leetcode 79.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.
Example:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
解法:
這個題跟前幾天做的Knight
那個題比較像,不過這個題是對二維陣列的搜尋,完成字串的匹配;
總體思路就是DFS,從左上角逐行開始往右下角搜尋,在搜尋過程中,對每一個落腳點進行四方位的搜尋,這裡需要注意一點我們需要避免往回走,所以就需要設定一個新的布林型別的二維陣列,用來記錄哪裡已經被走過,所以這次遍歷時候就不能再退回去;
同時在搜尋的過程中,我們如果可以判斷,待匹配字串的長度和已經搜尋到匹配的字串的長度一致,就證明我們已經搜尋成功,即可返回結果。
程式碼:
class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
if (word.empty()) return true;
if (board.empty() || board[0].empty()) return false;
vector<vector< bool> > visited(board.size(), vector<bool>(board[0].size(), false));
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[i].size(); ++j) {
if (search(board, word, 0, i, j, visited)) return true;
}
}
return false;
}
bool search(vector<vector<char> > &board, string word, int idx, int i, int j, vector<vector<bool> > &visited) {
if (idx == word.size()) return true;
if (i < 0 || j < 0 || i >= board.size() || j >= board[0].size() || visited[i][j] || board[i][j] != word[idx]) return false;
//標識不往回走
visited[i][j] = true;
bool res = search(board, word, idx + 1, i - 1, j, visited)
|| search(board, word, idx + 1, i + 1, j, visited)
|| search(board, word, idx + 1, i, j - 1, visited)
|| search(board, word, idx + 1, i, j + 1, visited);
//去除標識
visited[i][j] = false;
return res;
}
};