题目描述
Elma is learning chess figures.
She learned that a rook can move either horizontally or vertically. To enhance her understanding of rook movement Elma’s grandmother gave Elma an 8 × 8 chess board and asked her to find a way to move the rook from a1 to h8 making exactly n moves, so that all visited cells are different.
A visited cell is the initial cell a1 and each cell on which the rook lands after a move.
输入描述:
The input contains a single integer n (2 ≤ n ≤ 63) — the desired number of moves.
输出描述:
Output a space-separated list of n+1 visited cells in the order they are visited by the rook. All cells must be different. The list should start with a1 and end with h8. A solution always exists.
输入样例
4
输出样例
a1 f1 c1 c8 h8
说明
解题思路
这题给出的矩阵范围是8*8,起始位置的坐标是(1,1),要求到达目标点是(8,8)。给你一个数m,指你只能走的步数,车能够横向或者纵向走,在规定步数m时到达(8,8)这个坐标点,可能有多个解,但只需要求出任意一条解即可。
思路是用dfs,递归深搜,不会报超限,然后题目只要输出一条路径,所以要记录一下是否已经输出过了。然后点的位置可以用数组记录也可以用强转,emmm,代码如下
解题代码
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int m,l=0;
char x[9]={'0','a','b','c','d','e','f','g','h'};
void dfs(int x,int y,int t,int d[][15]){
int p[15][15]; //这里的话,我传二维数组的时候会改变原数组,不知道为什么,我也没有传指针,不知道如何解决就新开一个数组去使用,有些冗余,可能用vector会省去这个步骤。
for(int i=0;i<15;i++){
for(int j=0;j<15;j++){
p[i][j]=d[i][j];
}
}
if(x<1||x>8||y<1||y>8) return;
if(p[x][y])return;
p[x][y]=t;
if(t>m)return;
if(t==m&&x==8&&y==8&&l==0){
l=1;
for(int i=1;i<=m;i++){
for(int j=1;j<=8;j++){
for(int k=1;k<=8;k++){
if(p[j][k]==i){
cout<<char(96+j)<<k<<" ";
break;
}
}
}
}
return;
}
if(l==1){
return;
}
for(int i=1;i<=7;i++){
dfs(x-i,y,t+1,p);
dfs(x+i,y,t+1,p);
dfs(x,y-i,t+1,p);
dfs(x,y+i,t+1,p);
}
}
int main()
{
cin>>m;
m++;
int d[15][15]={0};
dfs(1,1,1,d);
}
题目来源
链接:https://ac.nowcoder.com/acm/contest/7865/A
来源:牛客网