POJ 2488(dfs+字典序)

来源:互联网 发布:php前端网站 编辑:程序博客网 时间:2024/06/09 13:43

poj2488

题意:

 问能不能不重复地走能遍历所有的棋格,走法按中国象棋马的方法。

分析: dfs+字典序输出...

我的字典序处理是用的String 来存,每次dfs后将该次有效遍历的地址加到串里面。从(0,0)开始。其他的就是基本的dfs知识~



#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <string>#define Max 30using namespace std;int n,m;int temp;int vis[Max][Max];int dir[8][2]={{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}};int dfs(int x,int y,int step,string tt){    if(step==temp)    {         cout<<tt<<endl<<endl;         return 1;    }    else    {        for(int i=0;i<8;i++)    {        int xx=x+dir[i][0];        int yy=y+dir[i][1];        char ans1=yy+'A';        char ans2=xx+'1';        if(xx>=0 && xx<n && yy>=0 && yy<m && vis[xx][yy]==0)        {            vis[xx][yy]=1;            if(dfs(xx,yy,step+1,tt+ans1+ans2))                return 1;            vis[xx][yy]=0;        }    }return 0;}}int main(){    int t;    cin>>t;    int ans=1;    while(t--)    {        scanf("%d%d",&n,&m);        temp=n*m;        memset(vis,0,sizeof(vis));        vis[0][0]=1;        printf("Scenario #%d:\n",ans++);        if(!dfs(0,0,1,"A1"))        printf("impossible\n\n");    }    return 0;}


    

0 0
原创粉丝点击