纪念第一次AC的dfs题

poj 2488

#include <stdio.h>
#include <string.h>
int n, p, q, flag;
int a[8] = { -1,1,-2,2,-2,2,-1,1 };//先下后上,因为从(1,1)开始,先下后上能尽可能避免超过限值,进而达到尽量先左后右的目的。
int b[8] = { -2,-2,-1,-1,1,1,2,2 };
int book[10][10];
typedef struct {
    char e;
    char f;
}coordinate;
coordinate coor[26];
int k;
void dfs(int x, int y, int step)
{
    int i;
    int nx, ny;
    coor[step].e = x + '0';
    coor[step].f = y + 'A' - 1;
    if (step == p * q)
    {
        flag = 1;
        return;
    }
    for (i = 0; i < 8; i++)
    {
        nx = x + a[i];
        ny = y + b[i];
        if (nx <1 || nx>p || ny<1 || ny>q)
            continue;
        if (book[nx][ny] == 0 && flag==0)
        {
            book[nx][ny] = 1;
            dfs(nx, ny, step + 1);
            book[nx][ny] = 0;
        }
        if (flag == 1)
            return;
    }
    return;
}
int main()
{
    int i;
    while (scanf("%d", &n) != EOF)
    {
        for (k = 1; k <= n; k++)
        {
            memset(book, 0, sizeof(book));
            scanf("%d%d", &p, &q);
            flag = 0;
            book[1][1] = 1;
            dfs(1, 1, 1);
            if (flag)
            {
                printf("Scenario #%d:\n", k);
                for (i = 1; i <= p * q; i++)
                {
                    printf("%c%c", coor[i].f, coor[i].e);
                }
                printf("\n\n");
            }
            else
                printf("Scenario #%d:\nimpossible\n\n", k);
        }
    }
    return 0;
}
上一篇:NX 模具 排气设计


下一篇:之前作品展示