洛谷 P1746 离开中山路
2024-08-29 00:56:33
题目背景
《爱与愁的故事第三弹·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行:最短到达目的地距离
输入输出样例
说明
20%数据:n<=100
100%数据:n<=1000
思路:bfs。dfs和spfa等图论算法都会gg。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n,ans=0x7f7f7f7f;
int sx,sy,tx,ty;
int map[][];
int dx[]={,,,-};
int dy[]={-,,,};
void dfs(int x,int y,int tot){
if(tot>=ans) return ;
if(x==tx&&y==ty){
ans=min(ans,tot);
return ;
}
for(int i=;i<;i++){
int cx=x+dx[i];
int cy=y+dy[i];
if(!map[cx][cy]&&cx>=&&cx<=n&&cy>=&&cy<=n){
map[cx][cy]=;
dfs(cx,cy,tot+);
map[cx][cy]=;
}
}
}
int main(){
scanf("%d",&n);
for(int i=;i<=n;i++)
for(int j=;j<=n;j++){
char x;cin>>x;
map[i][j]=x-'';
}
scanf("%d%d%d%d",&sx,&sy,&tx,&ty);
dfs(sx,sy,);
cout<<ans;
}
TLE的dfs
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n,ans=0x7f7f7f7f;
int sx,sy,tx,ty;
int map[][];
int dx[]={,,,-};
int dy[]={-,,,};
struct nond{
int x,y,step;
};
queue<nond>que;
int main(){
scanf("%d",&n);
for(int i=;i<=n;i++)
for(int j=;j<=n;j++){
char x;cin>>x;
map[i][j]=x-'';
}
scanf("%d%d%d%d",&sx,&sy,&tx,&ty);
nond tmp;tmp.x=sx;tmp.y=sy;tmp.step=;
que.push(tmp);map[sx][sy]=;
while(!que.empty()){
nond now=que.front();
que.pop();
for(int i=;i<;i++){
nond c;c.x=now.x+dx[i];
c.y=now.y+dy[i];
c.step=now.step+;
if(c.x==tx&&c.y==ty){ cout<<c.step;return ; }
if(c.x>=&&c.x<=n&&c.y>=&&c.y<=n&&!map[c.x][c.y]){
map[c.x][c.y]=;
que.push(c);
}
}
}
}
最新文章
- HDU5509 : Pattern String
- js的异步执行
- SpringMVC对异常进行全局处理,并区分对待ajax和普通请求
- Linux下PS命令详解
- 在hdfs上存取xml文件的实现代码
- 错误 1 Files 的值“ <; <; <; <; <; <; <; .mine”无效。路径中具有非法字符。
- leetcode:Reverse Bits
- java多线程总结一:线程的两种创建方式及优劣比较
- Servlet相关接口和Servlet的生命周期
- Ice_cream’s world III--2122
- jvm-初探
- Hadoop Security Authentication Terminology --Kerberos
- iOS开发之iOS7设置状态栏字体颜色
- S3C2440看门狗解析
- CMake必知必会
- poj-1146 ID codes
- SLAM+语音机器人DIY系列:(二)ROS入门——3.在ubuntu16.04中安装ROS kinetic
- 一个可以配置阴影方向和颜色的类 CardView 控件 SCardView
- 从入门到深入FIDDLER 2
- PHP 数组中取出随机取出指定数量子值集
热门文章
- Elasticsearch 7.0 正式发布,盘他!
- BA-强强联手江森自控携手日立空调(转载)
- Ajax-URL 防止数据缓存,添加时间戳
- [Tailwind] Style Elements on hover and focus with Tailwind’s State Variants
- springMVC3.0(文件上传,@RequestMapping加參数,@SessionAttributes,@ModelAttribute,转发,重定向,数值获取,传參,ajax,拦截器)
- hdu 4888 2014多校第三场1002 Redraw Beautiful Drawings 网络流
- Android通过Intent.ACTION_CLOSE_SYSTEM_DIALOGS监听Home按键消息
- 2015.04.27,外语,读书笔记-《Word Power Made Easy》 12 “如何奉承朋友” SESSION 35
- 错误 &#39;Cannot run program ";/home/uv/IDE/adt/sdk/platform-tools/adb";: error=2, No such file or directory
- UESTC--1265--宝贵资源(简单数学)