zoukankan      html  css  js  c++  java
  • DFS+单词搜索

    #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");
    }
  • 相关阅读:
    android音量知识总结
    android设置dialog透明度,黑暗度的方法
    获得图片资源总结
    Fragment使用案例
    activity主窗口与软键盘的交互模式
    AndroidManifest.xml中android:configChanges的简介
    2G,3G和4G网络类型了解
    安卓权限大全
    Spring
    多线程
  • 原文地址:https://www.cnblogs.com/z2529827226/p/11631403.html
Copyright © 2011-2022 走看看