六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 25|回复: 0

poj2488——A Knight's Journey

[复制链接]

升级  93.8%

309

主题

309

主题

309

主题

进士

Rank: 4

积分
969
 楼主| 发表于 2013-1-26 13:37:41 | 显示全部楼层 |阅读模式
深搜!可剪枝!
以后,写深搜的时候,最好用flag标记下,而且,回溯的时候,应采用本题写法!
#include<stdio.h>#include<string.h>int dir[][2]={{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}};bool map[30][30],flag;char path[100];int p,q;void dfs(int x,int y,int sum,int top){if(flag)return ;int i,tempx,tempy;if(sum==p*q){flag=true;return ;}for(i=0;i<8;i++){tempx=x+dir[i][0];tempy=y+dir[i][1];if(1<=tempx&&tempx<=q&&1<=tempy&&tempy<=p){if(map[tempx][tempy]){map[tempx][tempy]=false;path[top+1]=tempx-1+'A';path[top+2]=tempy+'0';dfs(tempx,tempy,sum+1,top+2);if(flag==false){    map[tempx][tempy]=true;}else return ;}}}}int main(){int T,i,sum,top;scanf("%d",&T);for(i=1;i<=T;i++){scanf("%d%d",&p,&q);sum=0;top=1;flag=false;printf("Scenario #%d:\n",i);memset(map,true,sizeof(map));map[1][1]=false;sum=1;path[1]='A';path[2]='1';top=2;dfs(1,1,sum,top);if(flag)for(int k=1;k<=p*q*2;k++)printf("%c",path[k]);else printf("impossible");printf("\n\n");}return 0;
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表