POJ 2488 A Knight's Journey

DFS,要求输出字典序最小的,注意扩展方向。

# include <cstdio>

# include <cstring>



# define N 26 + 5



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

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



int p, q, cnt;

bool finished;

char solu[N][2];

char vis[N][N];



void dfs(int x, int y)

{

    solu[cnt][0] = x, solu[cnt][1] = y;

    if (cnt == p*q)

    {

        finished = true;

        return ;

    }

    else

    {

        for (int i = 0; i < 8; ++i)

        {

            int nx = x + dx[i];

            int ny = y + dy[i];

            if (1<=nx&&nx<=p && 1<=ny&&ny<=q && !vis[nx][ny])

            {

                vis[nx][ny] = 1, ++cnt;

                dfs(nx, ny);

                if (finished) return;

                vis[nx][ny] = 0, --cnt;

            }

        }

    }



}



void solve(void)

{

    finished = false;



    for (int i = 1; i <= p; ++i)

                memset(vis[i]+1, 0, sizeof(int)*q);



    vis[1][1] = 1;

    cnt = 1;

    dfs(1, 1);

    if (finished)

    {

        printf("A1");

        for (int i = 2; i <= p*q; ++i)

            printf("%c%c", solu[i][1]-1+'A', solu[i][0]-1+'1');

        putchar('\n');

    }

    else

        puts("impossible");

}



int main()

{

    int T;



//    freopen("PKU2488.in", "r", stdin);



    scanf("%d", &T);

    for (int i = 1; i <= T; ++i)

    {

        if (i > 1) putchar('\n');

        printf("Scenario #%d:\n", i);

        scanf("%d%d", &p, &q);

        solve();

    }



    return 0;

}

你可能感兴趣的:(poj)