POJ 2488 A Knight's Journey (DFS)

poj-2488

题意:一个人要走遍一个不大于8*8的国际棋盘,他只能走日字,要输出一条字典序最小的路径
题解:
(1)题目上说的“The knight can start and end on any square of the board.”,是个坑点,其实要走字典序最小只需从A1开始遍历就行,因为从任意一点开始,只要能遍历完整个地图,那么A1也可以;
(2)要使字典序最小,那么遍历顺序一定要注意
int dr[8]={-1,1,-2,2,-2,2,-1,1};
int dc[8]={-2,-2,-1,-1,1,1,2,2};
(3)还有一个题上说1<=p*q<=26,那么如果p=1时,q=26时,所以数组要大于26;
AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn = 100;
int vis[maxn][maxn],Map[2][maxn];
int n,m,N,ans;
int flag;

int dr[8]={-1,1,-2,2,-2,2,-1,1};
int dc[8]={-2,-2,-1,-1,1,1,2,2};

bool judge(int x,int y){
	if(x>=1&&x<=n&&y>=1&&y<=m&&vis[x][y]==0)return true;
	else return false;
}

void dfs(int x,int y,int st){
	Map[0][st]=x;
	Map[1][st]=y;//记录路径 
	if(st>=N){
		flag=1;//满足条件标记 
		for(int i=1;i<=N;i++){
			printf("%c%d",Map[1][i]-1+'A',Map[0][i]);
		}cout<<endl;
		return;
	}
	for(int i=0;i<8;i++){
		int dx=x+dr[i];
		int dy=y+dc[i];
		if(judge(dx,dy)){
			Map[0][st]=x;
			Map[1][st]=y;
			vis[dx][dy]=1;
			dfs(dx,dy,st+1);
			if(flag)return;//一旦找到一组解就返回,不再进行回溯 
			vis[dx][dy]=0;
		}
	}
}

int main(){
	int t;
	while(cin>>t){
		int cas=0;
		while(t--){
			cin>>n>>m;
			memset(vis,0,sizeof(vis));
			printf("Scenario #%d:\n",++cas);
			flag=0;
			N=n*m;
			ans=0;
			vis[1][1]=1;
			dfs(1,1,1);
			if(!flag)cout<<"impossible\n"<<endl;
			else cout<<endl;
		}
	}
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值