LeetCode 79. 单词搜索(回溯DFS)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 79. 单词搜索(回溯DFS)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 題目
給定一個二維網格和一個單詞,找出該單詞是否存在于網格中。
單詞必須按照字母順序,通過相鄰的單元格內的字母構成,其中“相鄰”單元格是那些水平相鄰或垂直相鄰的單元格。同一個單元格內的字母不允許被重復使用。
示例: board = [['A','B','C','E'],['S','F','C','S'],['A','D','E','E'] ]給定 word = "ABCCED", 返回 true. 給定 word = "SEE", 返回 true. 給定 word = "ABCB", 返回 false.來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/word-search
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 回溯解題
class Solution { public:bool exist(vector<vector<char>>& board, string word) {bool ans = false;int i, j;for(i = 0; i < board.size(); i++)for(j = 0; j < board[0].size(); ++j)dfs(board,i,j,ans,word,0);return ans;}void dfs(vector<vector<char>> &b, int x, int y, bool &ans, string &word, int idx){if(ans == true)return;if(x < 0 || x == b.size() || y < 0 || y == b[0].size() || b[x][y] == '#' || b[x][y] != word[idx]) return;if(idx == word.size()-1){if(word[idx] == b[x][y])ans = true;return;}char ch = b[x][y];b[x][y] = '#';//標記走過dfs(b,x+1,y,ans,word,idx+1);dfs(b,x-1,y,ans,word,idx+1);dfs(b,x,y+1,ans,word,idx+1);dfs(b,x,y-1,ans,word,idx+1);b[x][y] = ch; //恢復現場} };總結
以上是生活随笔為你收集整理的LeetCode 79. 单词搜索(回溯DFS)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 735. 行星碰撞(栈
- 下一篇: 程序员面试金典 - 面试题 17.09.