POJ-2488 国际象棋马的走法 (深度优先搜索和回溯)

#include <stdio.h>
#define MAX 27
void dfs(int i, int j);

int dx[8] = {-1, 1, -2, 2, -2, 2, -1, 1};
int dy[8] = {-2, -2, -1, -1, 1, 1, 2, 2};
int marked[MAX][MAX];   //标记
int pathx[MAX];
int pathy[MAX];
int flag, step;
int p,q;

int main(void) {
    int n;
    int i = 0;
    int j, k;
    
    scanf("%d", &n);
    while (i++ < n) {      
        scanf("%d%d", &p, &q);
        for (j = 1; j <= p; j++) {
            for (k = 1; k <= q; k++)
                marked[j][k] = 0;
        }
        flag = 0;
        step = 0;
        dfs(1, 1);      //从(A, 1)开始搜索
        
        printf("Scenario #%d:\n", i);
        if (flag) {
            for (j = 1; j <= p * q; j++)
                printf("%c%d", pathy[j] + 'A' - 1, pathx[j]);
            printf("\n");
        }
        else 
            printf("impossible\n");
        printf("\n");
    }

}


void dfs(int i, int j) {
    int x, y;
    int k;
	if (flag == 1)  return;
    
  
    marked[i][j] = 1;         //标记
     
    step++;
    pathx[step] = i;
    pathy[step] = j;
    
    if (step == p * q)
    {
        flag = 1;
        return;
    }
    
    //注意:二维数组和棋盘的坐标x, y是反的
    for (k = 0; k < 8; k++) {
        x = i + dx[k];
        y = j + dy[k];
        if (marked[x][y] != 1 && x <= p && x>= 1 && y <= q && y >= 1) {
            dfs(x, y);
            step--;         //走错了回退时步数-1
        }
    }
    marked[i][j] = 0;       //撤销标记
}

    原文作者:骑士周游问题
    原文地址: https://blog.csdn.net/zhayujie5200/article/details/74276692
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞