字母游戏(dfs+剪枝)

问题 S: 【搜索】字母游戏

题目
一种单人玩的游戏,规则为:
在一个R行C列的方格上,每个方格中有一个A~Z的字母。游戏从左上角(第一行,第一列)位置开始,一步一步地向相邻(上、下、左、右)方格移动。唯一的限制是路径上的方格中的字母,每种字母只能出现1次。
游戏的目标是走尽可能长的路径。请你写程序算出指定棋盘上,可能走的最长步数。
输入
第1行两个整数R和C(1≤R,C≤20);
后面R行每行有C个字母,每行表示棋盘上的一行状态。
输出
有且只有一行,你计算出的最长步数。
思路
一开始使用bfs做,不行;后来使用dfs爆搜,因为使用了set,T了;然后我就加了一个剪枝if(maxn==26)return; 就从10000跑到了220;觉得跑得还不是很快,使用visit[ ]数组将set代替掉后,220->14;

#include <iostream>
#include <cstdio>
#include <vector>
#include <cmath>
#include <queue>
#include <set>
using namespace std;
int n,m;
char a[25][25];
struct node
{
    int x,y,step;
}temp;
bool visit[30];
int X[4]={0,0,-1,1};
int Y[4]={1,-1,0,0};
bool check(int x,int y)
{
    if(visit[a[x][y]-'a']) return false;
    if(x<1||x>n||y<1||y>m) return false;
    return true;
}
int maxn=0;
void solve(int x,int y,int step)
{
    maxn=max(maxn,step);
    if(maxn==26) return;
    for(int i=0;i<4;i++)
    {
        int nx=x+X[i],ny=y+Y[i];
        if(!check(nx,ny)) continue;
        visit[a[nx][ny]-'a']=true;
        solve(nx,ny,step+1);
        visit[a[nx][ny]-'a']=false;
    }
    return ;
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) cin>>a[i][j];
    visit[a[1][1]-'a']=true;
    solve(1,1,1);
    cout<<maxn<<endl;
}
/*
5 5
QWERT
YUIOP
ASDFG
HJKLZ
XCVBN
*/
发布了95 篇原创文章 · 获赞 7 · 访问量 8451

猜你喜欢

转载自blog.csdn.net/Spidy_harker/article/details/101482001