UDP广播协议叫吃饭


私信TA

用户名:Mustenaka

访问量:134872

签 名:

个人博客www.mustenaka.cn

等  级
排  名 12
经  验 23732
参赛次数 8
文章发表 196
年  龄 3
在职情况 学生
学  校 Sky_box
专  业 NE

  自我简介:

欢迎光临我的博客www.mustenaka.cn,Python,C#,U3D,C/C++开发合作可以找我

解题思路:
    利用结构体构建节点,其包含数据x,y位置,step走过的步数,way走过的方向存储。

    我这一套方法优化程度很低,但是相当好理解。

    利用BFS逐个进行搜索,这里需要记住的一点是搜索的顺序必须要按照DLRU这样的字典序进行排列,否则的话会产生一些错误数据。

    别忘了使用vis做地图标记,否则的话分分钟爆时。

参考代码:

#include<bits/stdc++.h>
#define hh ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;

const int maxn=1005;
/*
int dir[4][2]= {0,1,0,-1,1,0,-1,0};
//右,左,下,上,四个方向
这样子用方向会错,原因是需要写字典序最小的 
*/
int dir[4][2]={1,0,0,-1,0,1,-1,0};
//按照DLRU的字典序进行排列 
int vis[maxn][maxn];	//mark map
char mp[maxn][maxn];	//map array

int n,m;

struct state {
	int x,y;
	int step;
	string way;
};
state ans;	//答案变量

bool check(state s){
	if(!vis[s.x][s.y]&&s.x<n&&s.x>=0&&s.y<m&&s.y>=0){
		return true;
	}
	return false;
}

bool bfs() {
	queue<state> q;
	state now,next,st;
	st.x=0,st.y=0,st.step=0,st.way="";
	q.push(st);
	vis[st.x][st.y]=1;
	while(!q.empty()) {
		now=q.front();
		if(now.x==n-1&&now.y==m-1) {
			ans.x=now.x;
			ans.y=now.y;
			ans.step=now.step;
			ans.way=now.way;
			return true;
		}
		for(int i=0; i<4; i++) {
			next.x=now.x+dir[i][0];
			next.y=now.y+dir[i][1];
			next.step=now.step+1;
			switch(i) {
				case 0:
					next.way=now.way+"D";
					break;
				case 1:
					next.way=now.way+"L";
					break;
				case 2:
					next.way=now.way+"R";
					break;
				case 3:
					next.way=now.way+"U";
					break;
			}
			if(check(next)){
				q.push(next);
				vis[next.x][next.y]=1;
			}
		}
		q.pop();
	}
	return false;
}


int main() {
	hh;
	cin>>n>>m;
	memset(vis,0,sizeof(vis));
	memset(mp,0,sizeof(mp));
	for(int i=0; i<n; i++) {
		for(int j=0; j<m; j++) {
			cin>>mp[i][j];
			if(mp[i][j]=='1') {
				vis[i][j]=1;
			}
		}
	}
	if(bfs()){
		cout<<ans.step<<endl;
		cout<<ans.way<<endl;
	}else{
		cout<<'0'<<endl;
	}
	return 0;
}


 

0.0分

5 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区

没有写好题解,本题极容易忽视字典序:请按照'D', 'L', 'R', 'U'的方向来进行优先筛选排序
2019-07-23 21:46:48
大神牛逼6666666666666666
2019-07-21 21:26:38
  • «
  • 1
  • »