首页 > 其他 > 详细

DFS+单词搜索

时间:2019-10-07 17:49:52      阅读:96      评论:0      收藏:0      [点我收藏+]
#include <iostream>
#include <vector>
#include <string>
using namespace std;

class Solution {
private:
    int dir[4][2] = { {-1,0},{0,-1},{1,0},{0,1} };
    vector<vector<bool>>used;
public:
    bool isCheckMove(vector<vector<char>>&map,int x, int y) {
        return x >= 0 && x < map[0].size() && y >= 0 && y < map.size();
    }
    bool Search(vector<vector<char>>&map, string& word, int Index,int startX,int startY) {

        if (Index == word.length() - 1) {
            return word[Index] == map[startX][startY];
        }
        if (map[startX][startY] == word[Index]) {
            used[startX][startY] = true;
            for (int i = 0; i < 4; ++i) {
                int newX = startX + dir[i][0];
                int newY = startY + dir[i][1];
                if (isCheckMove(map, newX, newY) && !used[newX][newY] && Search(map, word, Index + 1, newX, newY))
                { 
                    return true;
                }
            }
            used[startX][startY] = false;
        }    
        return false;
    }
public:
    bool SearchWord(vector<vector<char>>&map,string& word)
    {
        used = vector<vector<bool>>(map.size(), vector<bool>(map[0].size(), false));
        for (int y = 0; y < map.size(); ++y) {
            for (int x = 0; x < map[y].size(); ++x) {
                if (map[y][x] == word[0]&&Search(map,word,0,y,x)) {
                    return true;
                }
                else {
                    continue;
                }
            }
        }
        return false;
    }
};

int main() {
    string word = "bfg";
    vector<vector<char>>map = {
        {a,b,c},
        {d,f,e},
        {g,s,h}
    };
    if (Solution().SearchWord(map, word)) {
        cout << "true" << endl;
    }
    else {
        cout << "false" << endl;
    }
    system("pause");
}

 

DFS+单词搜索

原文:https://www.cnblogs.com/z2529827226/p/11631403.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!