zoukankan      html  css  js  c++  java
  • 字符串的dfs

    因为没有回溯和vis记录,导致栈的超出
    所以,dfs中记得vis标记和回溯,可以达到剪枝的效果

    传送门
    用结构体只存储单词的首位和末尾
    然后如果在搜索中首位等于某位就不进行该情况的搜索,如果有匹配的,就搜索,和迷宫一样

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    const int maxn=10005;
    bool flag=false;
    bool vis[naxn];
    int cnt=0;
    struct node{
        char first;
        char endw;
    }word[maxn];
    void print(){
        printf("%s.
    ",flag==true?"Yes":"No");
    }
    void dfs(node a,int pos){
        //printf("%c %c
    ",a.first,a.endw);
        if(flag)return;
        if(a.endw=='m'){
            flag=true;
            return;
        }
        while(int i=0;i<cnt;i++){
            if(vis[i])continue;
            if(word[x].first==a.endw){
                if(word[x].first==word[x].endw||x==pos){
                    //如果说这个字母首位相同或者搜回到自己
                }else {
                    vis[x]=true;
                    dfs(word[x],x);
                    vis[x]=false;
                }
            }
        }
    
    }
    bool cmp(node a,node b){
        if(a.first==b.first)return a.endw<b.endw;
        return a.first<b.first;
    }
    void init(){
        cnt=0;
        flag=false;
    }
    int main(){
        char s[105];
        while(~scanf("%s",s)){
    
            if(s[0]=='0'){
                sort(word,word+cnt,cmp);
                for(int i=0;i<cnt;i++){
                    //printf("%c %c
    ",word[i].first,word[i].endw);
                   if(word[i].first=='b'&&flag==false){
                       dfs(word[i],i);
                   }else{
                       break;
                   }
                }
                print();
                init();
            }else{
                int len=strlen(s);
                word[cnt].first=s[0],word[cnt++].endw=s[len-1];
            }
    
        }
        return 0;
    }
    
  • 相关阅读:
    css3文字单位rem 设置文字大小
    JS实现多物体width缓冲运动实例
    vs 你不得不会的调试方式
    C# 常用修饰符
    富文本编辑器tinymce
    Swagger简单实例
    marquee标签详解
    table数据跑马灯效果
    SqlServer发布订阅
    ORM概述及常用ORM框架
  • 原文地址:https://www.cnblogs.com/Emcikem/p/11644434.html
Copyright © 2011-2022 走看看