博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
洛谷——P1746 离开中山路
阅读量:6920 次
发布时间:2019-06-27

本文共 2282 字,大约阅读时间需要 7 分钟。

P1746 离开中山路

题目背景

《爱与愁的故事第三弹·shopping》最终章。

题目描述

爱与愁大神买完东西后,打算坐车离开中山路。现在爱与愁大神在x1,y1处,车站在x2,y2处。现在给出一个n×n(n<=1000)的地图,0表示马路,1表示店铺(不能从店铺穿过),爱与愁大神只能垂直或水平着在马路上行进。爱与愁大神为了节省时间,他要求最短到达目的地距离(a[i][j]距离为1)。你能帮他解决吗?

输入输出格式

输入格式:

 

第1行:一个数 n

第2行~第n+1行:整个地图描述(0表示马路,1表示店铺,注意两个数之间没有空格)

第n+2行:四个数 x1,y1,x2,y2

 

输出格式:

 

只有1行:最短到达目的地距离

 

输入输出样例

输入样例#1:
30011011001 1 3 3
输出样例#1:
4

说明

20%数据:n<=100

100%数据:n<=1000

 

#include
#include
#include
#include
#define N 1200using namespace std;char ch;bool vis[N][N];int n,sx,sy,ex,ey,ans;int xx[4]={
0,0,1,-1},yy[4]={
1,-1,0,0};int read(){ int x=0,f=1; char ch=getchar(); while(ch<'0'||ch>'9') ch=getchar(); while(ch>='0'&&ch<='9'){x=x*10+ch-'0'; ch=getchar();} return x*f;}void dfs(int x,int y,int s){ if(x==ex&&y==ey) { ans=min(ans,s); return ; } if(x<1||y<1||x>n||y>n||vis[x][y]) return ; vis[x][y]=true;++s; for(int i=0;i<4;i++) { int fx=x+xx[i],fy=y+yy[i]; dfs(fx,fy,s); } vis[x][y]=false;}int main(){ n=read(); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) { cin>>ch; if(ch=='1') vis[i][j]=true; } sx=read(),sy=read(),ex=read(),ey=read(); ans=0x3f3f3f3f;dfs(sx,sy,0); printf("%d",ans); return 0;}
10分超时dfs

迷宫问题最好使用bfs,因为dfs可能会T的很惨、、

#include
#include
#include
#include
#include
#define N 2200using namespace std;char ch;bool vis[N][N];int xx[4]={
0,0,1,-1},yy[4]={
1,-1,0,0};int n,sx,sy,ex,ey,ans,tail,head,q[N*N][3],d[N][N];int read(){ int x=0,f=1; char ch=getchar(); while(ch<'0'||ch>'9') ch=getchar(); while(ch>='0'&&ch<='9'){x=x*10+ch-'0'; ch=getchar();} return x*f;}int main(){ n=read(); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) { cin>>ch; if(ch=='1') vis[i][j]=true; } sx=read(),sy=read(),ex=read(),ey=read(); memset(d,0x3f3f3f3f,sizeof(d));d[sx][sy]=0; q[tail][1]=sx,q[tail][2]=sy,++tail; while(head
n||fy>n) continue; if(d[fx][fy]>(d[x][y]+1)) d[fx][fy]=d[x][y]+1,q[tail][1]=fx,q[tail][2]=fy,++tail; } }}

 

转载于:https://www.cnblogs.com/z360/p/7575342.html

你可能感兴趣的文章
西安协同工作流如何接入其他系统的组织机构
查看>>
KVO
查看>>
LAMP原理架构解析(二):Php操作Mysql数据库
查看>>
二十年后的回眸(8)——晋级的炒更之旅
查看>>
京东商城IPO 大平台局面形成的几个因素
查看>>
九、Linux系统安装和常见故障排除
查看>>
linux+nginx+mysql+php高性能服务器搭建
查看>>
awk内置变量2-2
查看>>
我的友情链接
查看>>
MFC中的DC、CDC、HDC、句柄、设备上下文的不同意思,适合初学者参考
查看>>
mysql复制
查看>>
Spring中配置事务的几种方式
查看>>
php 新漏洞
查看>>
asp.net5 的应用启动
查看>>
HTMLDocument和XMLDocument 的children
查看>>
线性判别分析(LDA)算法总结
查看>>
LINUX/CENTOS 修改mysql的root用户密码
查看>>
linux/centos 搭建本地yum服务器
查看>>
RH436 UNIT 1 CLUSTERS AND STORAGE
查看>>
CentOS 6.5 启动级别
查看>>