1455: [蓝桥杯2019初赛]迷宫

2019省赛A组第4题 迷宫(BFS+DFS)

题目链接http://oj.ecustacm.cn/problem.php?id=1455

下面是答案提交的代码

#include<iostream>
using namespace std;
int main() {
    
    

	cout << "DDDDRRURRRRRRDRRRRDDDLDDRDDDDDDDDDDDDRDDRRRURRUURRDDDDRDRRRRRRDRRURRDDDRRRRUURUUUUUUULULLUUUURRRRUULLLUUUULLUUULUURRURRURURRRDDRRRRRDDRRDDLLLDDRRDDRDDLDDDLLDDLLLDLDDDLDDRRRRRRRRRDDDDDDRR";
	return 0;
}

用DFS来解题


//其中D、U、L、R 分别表示向下、向上、向左、向右走。\
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
char a[35][55];
char b[4] = {
    
     'D','L','R','U' };
bool vis[35][55] = {
    
     0 };
int fx[4][2] = {
    
     {
    
    1,0},{
    
    0,-1},{
    
    0,1},{
    
    -1,0} };
int mins[35][55];
int p[2000] = {
    
     0 }, q[2000] = {
    
     0 };
int minn=2000, ans=0;//D<L<R<U。
bool fw(int x, int y) {
    
    
	if (x > 0 && x <=30 && y > 0 && y <= 50)
		return true;
	return false;

}
void dfs(int x, int y) {
    
    
	if (ans > minn){
    
    
		return;
	}
	if (x == 30&& y == 50) {
    
    
		if (minn > ans) {
    
    
			minn = ans;
			for (int i = 0; i < ans; i++) {
    
    
				p[i] = q[i];
			}
		}
		return;
	}
	vis[x][y] = 1;
	for (int i = 0; i < 4; i++) {
    
    
		int xx = x + fx[i][0], yy = y + fx[i][1];
		if (fw(xx, yy) && a[xx][yy] != '1' && !vis[xx][yy]&&ans+1<=mins[xx][yy]) {
    
    
			q[ans++] = i;
			mins[xx][yy] = ans;
			dfs(xx, yy);
			ans--;
		}
	}
	vis[x][y] = 0;
}
int main() {
    
    
	for (int i = 1; i <= 30; i++) {
    
    
		for (int j = 1; j <= 50; j++) {
    
    
			cin >> a[i][j];
		}
	}
	memset(mins, 0x3f, sizeof(mins));
	dfs(1, 1);
	cout << minn << endl;
	for (int i = 0; i < minn; i++) {
    
    
		cout << b[p[i]];
	}
	return 0;
}



用BFS来解题

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstring>
#include<queue>
using namespace std;
typedef struct Node {
    
    
	int x, y;
	string s;
	Node(int xx,int yy,string ss):x(xx),y(yy),s(ss){
    
    }
}node;
queue<node> q;
char a[35][55];
char b[4] = {
    
     'D','L','R','U' };
bool vis[35][55] = {
    
     0 };
int fx[4][2] = {
    
     {
    
    1,0},{
    
    0,-1},{
    
    0,1},{
    
    -1,0} };
bool fw(int x, int y) {
    
    
	if (x > 0 && x <= 30 && y > 0 && y <= 50)
		return true;
	return false;

}
void bfs() {
    
    
	node now(1, 1, "");
	q.push(now);
	while (!q.empty()) {
    
    
		node temp = q.front();
		q.pop();
		if (temp.x == 30 && temp.y == 50) {
    
    
			cout << temp.s;
			return;
		}
		for (int i = 0; i < 4; i++) {
    
    
			int xx = temp.x + fx[i][0], yy = temp.y + fx[i][1];
			if (fw(xx, yy) && a[xx][yy] != '1' && !vis[xx][yy]) {
    
    
				node neww(xx, yy, temp.s + b[i]);
				q.push(neww);
				vis[xx][yy] = 1;
			}
		}
	}



	
}
int main() {
    
    
	for (int i = 1; i <= 30; i++) {
    
    
		for (int j = 1; j <= 50; j++) {
    
    
			cin >> a[i][j];
		}
	}
	vis[1][1] = 1;
	bfs();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46028214/article/details/113183741