A Knight's Journey+dFS

#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;


int ok=0;
int k;
int n,m;
int f[50][50];
int trackk[400][3];   


int dx[]={-2,-2,-1,-1,1,1,2,2};
int dy[]={-1,1,-2,2,-2,2,-1,1};




int is_board(int r, int c)
{

if ( r>=1 && r<=n && c>=1 && c<=m) return 1;
return 0;
}


int isend()
{
int i,j;
for (i=1;i<=n;i++)
{
for (j=1;j<=m;j++)
{
if (f[i][j]==0)  return 0;
}
}
return 1;
}


int bfs(int r,int c)
{

if (isend())
{ ok=1; 
return 0;
}

if (ok) return 0;
int i;
for (i=0;i<8;i++)
{
if (  is_board(r+dx[i],c+dy[i]) && f[r+dx[i]][c+dy[i]]==0 )
{nal
f[r+dx[i]][c+dy[i]]=1;

trackk[k][1]=r+dx[i];
trackk[k][2]=c+dy[i];
k++;

bfs(r+dx[i],c+dy[i]); 
if (ok) return 0;

k--;
f[r+dx[i]][c+dy[i]]=0;
}
}

return 0;
}






int main()
{

int t;

int i,kk;
kk=2;

scanf("%d",&t);
for (kk=1;kk<=t;kk++)
{
ok=0;
memset(f,0,sizeof(f));
memset(trackk,0,sizeof(trackk));
trackk[1][1]=1;
trackk[1][2]=1;
scanf("%d%d",&m,&n);
printf("Scenario #%d:\n",kk);
f[1][1]=1;
 
k=2;
bfs(1,1);
 
if (ok)

for (i=1;i<=n*m ;i++)
{
printf("%c%d",trackk[i][1]+64 ,trackk[i][2]);
}
}


else printf("impossible");


printf("\n\n"); 
}

return 0;

你可能感兴趣的:(A Knight's Journey+dFS)