POJ 2488 A Knight's Journey DFS 深搜回溯

来源:互联网 发布:医疗器械公司软件 编辑:程序博客网 时间:2024/05/16 12:44
/***  DFS 深搜回溯*  题意: 骑士走遍所有各自r*c,且每个格子只走一次。 如果可以走完*  输出字典序最小的path,不能就impossible*  在每次向下dfs的,记录path,当走到叶子节点的时候,也就是不能再向下走的时候,return*  用cur记录已踩格子数,当cur等于tot的时候说明全部踩过,再把得出的str和ans比较,*  如果字典序小的话,替换ans。  最后按要求输出就行了**  这里要小心的是,确定并铭记你的地图行列各表示什么的是什么, 别弄混了!*/#include <cstdio>#include <cstring>#include <cmath>#include <string>#include <algorithm>#define INF 0x7fffffff#define MAXS 27#define LL long longusing namespace std;char ans[60], str[60];int vis[MAXS][MAXS], path[MAXS][2];int tot, r, c;int dir[8][2] = {{1, 2}, {-1, 2}, {1, -2}, {-1, -2},                {2, 1}, {2, -1}, {-2, 1}, {-2, -1}};void merge() {    for(int i = 0, c = 0; c < tot*2; i ++, c += 2) {        str[c] = path[i][0] + 'A' - 1;        str[c+1] = path[i][1] + '0';    }}bool judge(int x, int y) {    return (x >= 1 && x <= r && y >= 1 && y <= c) ? true : false ;}void dfs(int cur, int curPath) {    int x, y;    x = path[curPath - 1][0];    y = path[curPath - 1][1];    if(cur == tot) {        merge();        if(strcmp(ans, str) == 1)            strcpy(ans, str);        return ;    }    int nx, ny;    for(int i = 0; i < 8; i ++) {        nx = x + dir[i][0];        ny = y + dir[i][1];        if(judge(nx, ny) && !vis[nx][ny]) {            vis[nx][ny] = 1;            path[curPath][0] = nx;            path[curPath][1] = ny;            dfs(cur + 1, curPath + 1);            vis[nx][ny] = 0;        }    }    return ;}int main(){    int T, scenario = 1;    scanf("%d", &T);    for( ; scenario <= T; scenario ++) {        for(int i = 0; i < MAXS; i ++)            ans[i] = 127;        memset(vis, 0, sizeof(vis));        scanf("%d%d", &c, &r);        tot = r * c;        printf("Scenario #%d:\n", scenario);        path[0][0] = path[0][1] = 1;        vis[1][1] = 1;        dfs(1, 1);        if(ans[1] == 127)            printf("impossible\n");        else {            for(int i = 0; i < tot * 2; i ++)                printf("%c", ans[i]);            printf("\n");        }        printf("\n");    }    return 0;}