zufeoj_骑士巡游问题

题目链接:http://acm.ocrosoft.com/problem.php?cid=1222&pid=33

题目描述

输入 n ( 1< = n < = 10 ) 代表棋盘的规模就是 n*n 的规模,骑士永远从 (1,1) 出发,要求骑士走遍所有棋盘的格子
输出 骑士的走法(遍历棋盘的所有格子) 

注意方向:

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

输入

输出

样例输入

5

样例输出

1 10 5 18 3
14 19 2 11 6
9 22 13 4 17
20 15 24 7 12
23 8 21 16 25

#include<iostream>
using namespace std;
int n;
int dir[8][2]={{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2}};
int ans[11][11];
bool vis[11][11];
bool flag=0;
void dfs(int x,int y,int cnt){
    if(cnt>n*n){
        for(int i=1;i<=n;i++){
            for(int j=1;j<n;j++){
                cout<<ans[i][j]<<" ";
            }
            cout<<ans[i][n]<<endl;
        }
        flag=1;
        return;
    }
    for(int i=0;i<8;i++){
        int xx=x+dir[i][0];
        int yy=y+dir[i][1];
        if(xx>=1&&xx<=n&&yy>=1&&yy<=n&&vis[xx][yy]==0){
            vis[xx][yy]=1;
            ans[xx][yy]=cnt;
            dfs(xx,yy,cnt+1);
            if(flag==1){
                return;
            }
            vis[xx][yy]=0;
        }
    }
}
 
int main(){
    cin>>n;
    ans[1][1]=1;
    vis[1][1]=1;
    dfs(1,1,2);
    return 0;
} 

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