迷宫和马的遍历

迷宫

#include <bits/stdc++.h>
using namespace std;

int a[6][6];
int b[6][6];
int dx[4]={0,0,1,-1};
int dy[4]={-1,1,0,0};
int t,fx,fy,sx,sy,T,n,m,l,r;
void walk(int x,int y){
	if(x==fx&&y==fy){
		t++;
		return;
	}else{
		for(int i=0;i<=3;i++){
			if(b[x+dx[i]][y+dy[i]]==0&&a[x+dx[i]][y+dy[i]]==1){
				b[x][y]=1;//标记已经走过的方格
				walk(x+dx[i],y+dy[i]);//嵌套函数
				b[x][y]=0;//恢复
			}
		}
	}
}
int main(){
	cin>>n>>m>>T;
	for(int p=1;p<=n;p++){
		for(int q=1;q<=m;q++){
			a[p][q]=1;
		}
	}
	cin>>sx>>sy;
	cin>>fx>>fy;
	for(int u=1;u<=T;u++){
		cin>>l>>r;
		a[l][r]=0;//标记障碍物
	}
	walk(sx,sy);
	cout<<t;
	return 0;
}

马的遍历

#include<bits/stdc++.h>
using namespace std;

queue<int> o,p,q;
int n,m,X,Y,a[500][500];
bool vis[500][500];
int xx[9]={0,-1,-2,-2,-1,1,2,2,1};
int yy[9]={0,-2,-1,1,2,2,1,-1,-2};

void W()
{
	int x,y,step;
	while(o.empty()==0){
		x=o.front();
		y=p.front();
		step=q.front();
		a[x][y]=step;
		o.pop();
		p.pop();
		q.pop();
		for(int i=1;i<=8;i++){
			if(x+xx[i]>=1&&x+xx[i]<=n&&y+yy[i]>=1&&y+yy[i]<=m&&vis[x+xx[i]][y+yy[i]]==0){
				vis[x+xx[i]][y+yy[i]]=1;
				o.push(x+xx[i]);
				p.push(y+yy[i]);
				q.push(step+1);
			}
		}
	}
}
int main(){
	cin>>n>>m>>X>>Y;
	o.push(X);
	p.push(Y);
	q.push(0);
	vis[X][Y]=1;
	W();
	
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			if(vis[i][j]==0){
				cout<<"-1 ";
			}else{
				cout<<a[i][j]<<" ";
			}
		}
		cout<<endl;
	}
	return 0;
}

用STL的queue

o.front() 返回队列的首元素的值

o.pop()删除队列首元素但不返回其值

o.push(x)在队尾压入新元素,x为新元素

o.empty()如果队列为空返回true,否则返回false

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值