马走日问题(dfs最短字典序)

题意:输出马遍历象棋棋盘的最小字典序路径(起点任意)。

难点: 怎么才能输出最小字典序的路径?

解决:最小:按从小到大的顺序设置方向向量

           只输出一个:将dfs标记为bool类型  到不了底的路径return false, 可以搜到底的路径return true(return了就不会继续往下循环方向了)。

易错:x是横向,对应q;y是纵向,对应p。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
using namespace std;

#define x first
#define y second

typedef pair<char, int> PII;
vector<PII> res;
const int N = 30;
bool st[N][N];
int p, q, cnt = 1;
int dx[] = {-2, -2, -1, -1, 1, 1, 2, 2}, dy[] = {-1, 1, -2, 2, -2, 2, -1, 1};

bool dfs(int x, int y, int u){
	
	res.push_back({x + 65, y + 1});   //顺序 
	
	if(u >= p * q){
		for(auto a: res) cout << a.x << a.y;
		cout << endl; 
		return true;
	}
	
	st[x][y] = true;
	
	
	for(int i = 0; i < 8; ++ i){
		int nx = x + dx[i], ny = y + dy[i];
		//if(u <= 4)cout << u << ' ' << nx << ' '<< ny << endl;
		if(nx >= q || nx < 0 || ny >= p || ny < 0) continue;  //x是行 y是列 
		
		if(!st[nx][ny]){
			if(dfs(nx, ny, u + 1) ) return true;  //是这一步阻断了后续的搜索			
		} 
	}
	st[x][y] = false;   //出循环说明无路可走
	res.pop_back();     //弹出‘错误’的点
    return false;       //返回false
}

int main(){
	  int t;
	  cin >> t;
	  while(t--){
	  	cin >> p >> q;
	  	cout << '#' << cnt << ':' << endl;
	    if(!dfs(0, 0, 1)) cout << "none" << endl;
	  	memset(st, 0, sizeof st);
	  	res.clear();
	  	++ cnt;
	  }
	
     return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值