习题 7-15 最大的数(Biggest Number, UVa11882)

原题链接:https://vjudge.net/problem/UVA-11882
分类:迭代剪枝
备注:A*算法

利用剩余可能的最大长度判断一下是否继续搜,如果当前长度加上这个长度后等于目前答案长度,比较一下当前值和答案前缀。

#include<bits/stdc++.h>
using namespace std;
const int dir[][2]={{0,1},{1,0},{-1,0},{0,-1}};
int row,col,vis[20][20],len[20][20];
char g[20][20];
string ans;
inline char read(){
    char ch=getchar();
    while(ch==' '||ch=='\n')ch=getchar();
    return ch;
}
struct node{int x,y,len;};
inline int leftMaxLen(int x,int y){
    int tag[20][20]={0},res=0;
    tag[x][y]=1;
    queue<node>q;
    q.push(node{x,y});
    while(!q.empty()){
        node u=q.front(); q.pop(); res++;
        for(int i=0;i<4;i++){
            int row2=u.x+dir[i][0];
            int col2=u.y+dir[i][1];
            if(row2<1||row2>row||col2<1||col2>col||g[row2][col2]=='#'||vis[row2][col2]||tag[row2][col2])continue;
            tag[row2][col2]=1;
            q.push(node{row2,col2});
        }
    }
    return res;
}
void dfs(string& s,int x,int y){
    int len=leftMaxLen(x,y),flg=0;
    if(s.length()+len<ans.length()||(s.length()+len==ans.length()&&s<ans.substr(0,s.length())))return;
    s+=g[x][y]; vis[x][y]=1;
    for(int i=0;i<4;i++){
        int row2=x+dir[i][0];
        int col2=y+dir[i][1];
        if(row2<1||row2>row||col2<1||col2>col||g[row2][col2]=='#'||vis[row2][col2])continue;
        dfs(s,row2,col2); flg=1;
    }
    if(!flg&&(ans.length()<s.length()||(ans.length()==s.length()&&ans<s)))ans=s;
    s.pop_back();
    vis[x][y]=0;
}
int main(void){
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    while(~scanf("%d %d",&row,&col)&&row){
        for(int i=1;i<=row;i++)
            for(int j=1;j<=col;j++)
                g[i][j]=read();
        ans="";
        for(int i=1;i<=row;i++)
            for(int j=1;j<=col;j++){
                if(g[i][j]=='#')continue;
                memset(vis,0,sizeof(vis));
                string tmp="";
                dfs(tmp,i,j);
            }
        printf("%s\n",ans.c_str());
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JILIN.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值