JZOJ P5793. 【NOIP2008模拟】小S练跑步

版权声明:喜欢请点个大拇指,感谢各位dalao。弱弱说下,转载要出处呦 https://blog.csdn.net/qq_35786326/article/details/82943858


题目:

传送门


分析:

考试的时候,用 d f s dfs 死磕,结果 10 10 分凉掉,然后用 b f s bfs 乱敲一下就 A A . . ..
根本没有顾及到 d f s dfs 的面子嘛


代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>  
#include<cstdlib>
#include<algorithm>
#include<set>
#include<queue>
#include<vector>
#include<map>
#include<list>
#include<ctime>
#include<iomanip>
#include<string>
#include<bitset>
#include<deque>
#include<set>
#define LL long long
#define h happy
#define ch cheap
using namespace std;
inline LL read() {
    LL d=0,f=1;char s=getchar();
    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
    while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();}
    return d*f;
}
int min(int x,int y) {return x<y?x:y;}
int c[501][501],tf[501][501];
int dx[5]={0,-1,1,0,0},dy[5]={0,0,0,-1,1};
int ans;
int n,m;
struct node{int x,y,w;};
queue<node> q;
void bfs()
{
	q.push((node){1,1,0});
	while(q.size())
	{
		int x=q.front().x,y=q.front().y,w=q.front().w;
		q.pop();
		for(int k=1;k<=4;k++)
		{
			int d=1;
			while(x+dx[k]*d<=n&&x+dx[k]*d>0&&y+dy[k]*d<=m&&y+dy[k]*d>0&&c[x+dx[k]*(d-1)][y+dy[k]*(d-1)]!=k&&c[x+dx[k]*d][y+dy[k]*d])
			{
				if(!tf[x+dx[k]*d][y+dy[k]*d])
				{
					tf[x+dx[k]*d][y+dy[k]*d]=1;
					q.push((node){x+dx[k]*d,y+dy[k]*d,w+1});
					if(x+dx[k]*d==n&&y+dy[k]*d==m) {ans=w;return;}
				}
				d++;
			}
		}
	}
	ans=-1;
	return;
}
int main()
{
	n=read();m=read();
	char ch;
	for(int i=1;i<=n;i++)
	  for(int j=1;j<=m;j++)
	    {
	    	cin>>ch;
	    	c[i][j]=(ch=='U'?1:(ch=='D'?2:(ch=='L'?3:(ch=='R'?4:0))));
		}
	c[n][m]=1;
	if(c[1][1]=='S') {printf("No Solution");return 0;}
	else bfs();
	if(ans==-1) printf("No Solution");
	else cout<<ans;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35786326/article/details/82943858