C++ Easy Chess

题目描述

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
来源:牛客网

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

祖安大龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值