AcWing 844. 走迷宫(BFS or DP)

Posted MangataTS

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AcWing 844. 走迷宫(BFS or DP)相关的知识,希望对你有一定的参考价值。

题目链接

https://www.acwing.com/problem/content/description/846/

思路

直接用BFS跑一个最短路就好了,因为边权都是为1的,并且每次只有四个方向选择

代码

#include<bits/stdc++.h>
using namespace std;
//----------------自定义部分----------------
#define ll long long
#define mod 1000000007
#define endl "\\n"
#define PII pair<int,int>

int dx[4]=0,-1,0,1,dy[4]=-1,0,1,0;

ll ksm(ll a,ll b) 
	ll ans = 1;
	for(;b;b>>=1LL) 
		if(b & 1) ans = ans * a % mod;
		a = a * a % mod;
	
	return ans;


ll lowbit(ll x)return -x & x;

const int N = 1e2+10;
//----------------自定义部分----------------
int n,m,q,a[N][N],vis[N][N];

struct Node
	int x,y,step;
;
bool check(int x,int y)
	if(x >= 1 && x <= n && y >= 1 && y <= m && a[x][y] == 0) return true;
	return false;


int bfs(int sx,int sy)
	queue<Node> que;
	que.push(sx,sy,0);
	while(!que.empty()) 
		Node p = que.front();
		que.pop();
		if(p.x == n && p.y == m) return p.step;
		if(vis[p.x][p.y]) continue;
		vis[p.x][p.y] = true;
		for(int i = 0;i < 4; ++i) 
			int nx = p.x+dx[i];
			int ny = p.y+dy[i];
			if(check(nx,ny) && !vis[nx][ny])
				que.push(nx,ny,p.step+1);
			
		
	 
	return -1;


int main()

	std::ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
	std::cout.tie(nullptr);
	cin>>n>>m;
	for(int i = 1;i <= n; ++i) 
		for(int j = 1;j <= m; ++j) 
			cin>>a[i][j];
		
	
	cout<<bfs(1,1)<<endl;
	return 0;

以上是关于AcWing 844. 走迷宫(BFS or DP)的主要内容,如果未能解决你的问题,请参考以下文章

AcWing 844. 走迷宫

Acwing844.走迷宫

Acwing844.走迷宫

Acwing844.走迷宫

844. 走迷宫

ACwing(基础)--- 走迷宫(bfs)