BFS马在棋盘上移动的方法

the reason of failure:1、输出无法回溯。

how to solve:

1、p[v.r][v.c]=u;

while(1){
nodes.push_back(u);
if(walked[u.r][u.c]==0)break;
u=p[u.r][u.c];
} 通过把值放入p数组,然后通过回溯读取

question:

where is difficult:

key point:建立一个包含2个int的结构Node,然后根据题意建立二维表格,广搜主要用于求最优解

#include <stdio.h>
#include <string.h> 
#include <queue>
#include <iostream>
#include <vector> 
using namespace std;
int r0,c0,r1,c1,r2,c2,dir0;
struct Node{
	int r,c;
	Node(int rr,int cc){
	r=rr;
	c=cc;		
	}
	Node(){};
};
Node v;
queue<Node>q;
int walked[10][10];
Node p[10][10];
int d[10][10];  
Node walk1(Node &u,int i){
	switch(i){
		case 1:return Node(u.r+1,u.c+2);
		case 2:return Node(u.r+2,u.c+1);
		case 3:return Node(u.r+1,u.c-2);
		case 4:return Node(u.r+2,u.c-1);
		case 5:return Node(u.r-1,u.c+2);
		case 6:return Node(u.r-2,u.c+1);
		case 7:return Node(u.r-1,u.c-2);
		case 8:return Node(u.r-2,u.c-1);
	}
}
bool insert(int a,int b){
	
	
	if(a>0&&a<9&&b>0&&b<9)      //搞清楚界限 
	return true;
	else
	return false;
}
void print(Node u){
	vector<Node>nodes;
		while(1){
			nodes.push_back(u);
			if(walked[u.r][u.c]==0)break;
			u=p[u.r][u.c];
		}
	for(int i=nodes.size()-1;i>=0;i--){
		cout << "(" << nodes[i].r<<"," << nodes[i].c << ")";
	}
}
void solve(){
	int c=26;
	Node u(r0,c0);
	memset(walked,-1,sizeof(walked));
	walked[u.r][u.c]=0;
	q.push(u);
	while(!q.empty()){          //BFS这里判断队列是否为空用while循环
		u=q.front();
		q.pop();
		//printf("(%d%d%d)",u.r,u.c,u.f1);
	 	r1=u.r;
	 	c1=u.c;
	 	//printf("(%d%d)",r1,c1);
	 	if(r1==r2&&c1==c2){
	 		//printf("%d%d",u.r,u.c);
	 		return print(u);
		 }
	 	for(int i=1;i<=8;i++){
	 		v=walk1(u,i);
	 		//printf("(%d)",v.f1);
	 		//printf("%d%d",v.r,v.c);
	 		if(walked[v.r][v.c]<0&&insert(v.r,v.c)){
	 			//printf("(%d,%d)",v.r,v.c);
	 			walked[v.r][v.c]=1;
	 			p[v.r][v.c]=u;
	 			q.push(v);
	 			
			 }
		 }
	}
	
}
int main(){
	freopen("in.txt","r",stdin);
	freopen("out.txt","w",stdout);
	    scanf("(%d,%d) (%d,%d)",&r0,&c0,&r2,&c2);
		//printf("(%d,%d) (%d,%d)",r0,c0,r2,c2);
		solve();
		return 0;
	}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值