poj 2488 A Knight's Journey

poj 2488 A Knight's Journey
http://acm.pku.edu.cn/JudgeOnline/problem?id=2488
poj 2488 A Knight's Journey
简单的BFS

Source Code

Problem: 2488 User: lovecanon
Memory: 324K Time: 16MS
Language: GCC Result: Accepted
  • Source Code
    
        
          
          
          
          
    #include<stdio.h>
    #include<string.h>


    typedef struct node
    {
    int r;
    int c;
    }node;
    node step[50];

    int m,n,found;
    const int dx[]={-2,-2,-1,-1,1,1,2,2},dy[]={-1,1,-2,2,-2,2,-1,1};

    int visited[50][50],dep;

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

    void output()
    {
    int i;
    if(found==0) { printf("impossible\n\n");return; }
    for(i=1;i<=m*n;i++)
    printf("%c%d",step[i].r-1+'A',step[i].c);
    printf("\n\n");

    }

    void solve(int r,int c){
    if(!found){
    visited[r][c]=1;
    step[dep].r=r;
    step[dep].c=c;

    if(dep>=m*n){
    found=1;return;
    }

    else{
    int nextr,nextc,i;
    for(i=0;i<8;i++)
    {
    nextr=r+dx[i];
    nextc=c+dy[i];
    if(ok(nextr,nextc)&&!visited[nextr][nextc])
    {
    dep++;
    solve(nextr,nextc);
    dep--;
    }
    }
    visited[r][c]=0;
    }
    }

    }

    int main()
    {
    int T,count=1;
    scanf("%d",&T);
    while(count<=T)
    {
    scanf("%d%d",&n,&m);
    dep=1;found=0 ;
    memset(visited,0,sizeof(visited));
    solve(1,1);
    printf("Scenario #%d:\n",count);
    output();
    count++;
    }
    return 0;
    }


你可能感兴趣的:(poj 2488 A Knight's Journey)