NC25031. [USACO 2007 Dec S]Mud Puddles
描述
输入描述
* Line 1: Three space-separate integers: X, Y, and N.
* Lines 2..N+1: Line i+1 contains two space-separated integers: Ai and Bi
输出描述
* Line 1: The minimum distance that Farmer John has to travel to reach Bessie without stepping in mud.
示例1
输入:
1 2 7 0 2 -1 3 3 1 1 1 4 2 -1 1 2 2
输出:
11
说明:
Bessie is at (1, 2). Farmer John sees 7 mud puddles, located at (0, 2); (-1, 3); (3, 1); (1, 1); (4, 2); (-1, 1) and (2, 2).C++14(g++5.4) 解法, 执行用时: 19ms, 内存消耗: 4456K, 提交时间: 2019-07-13 12:46:21
#include<bits/stdc++.h> using namespace std; typedef long long ll; int mark[1005][1005],dx[5]={0,1,0,-1,0},dy[5]={0,0,1,0,-1}; struct node{ int a,b; }; queue<node>q; int main(){ int x,y,n,u,v; scanf("%d%d%d",&x,&y,&n); x+=501;y+=501; for(int i=1;i<=n;i++){ scanf("%d%d",&u,&v); u+=501;v+=501; mark[u][v]=-1; } mark[501][501]=1; q.push({501,501}); while(!q.empty()){ node t=q.front(); q.pop(); for(int i=1;i<=4;i++){ int a=t.a+dx[i],b=t.b+dy[i]; if(a<0||a>1004||b<0||b>1004)continue; if(!mark[a][b]){ mark[a][b]=mark[t.a][t.b]+1; q.push({a,b}); } if(a==x&&b==y){ printf("%d\n",mark[a][b]-1); return 0; } } } return 0; }
C++11(clang++ 3.9) 解法, 执行用时: 419ms, 内存消耗: 4460K, 提交时间: 2019-07-14 20:59:17
#include<bits/stdc++.h> using namespace std; int x,y,n,m[1005][1005],px,py,d; int main(){ cin>>x>>y>>n; for(int i=0;i<1005;i++){ for(int j=0;j<1005;j++){ m[i][j]=-1; } } m[502][502]=0; for(int i=0;i<n;i++){ cin>>px>>py; m[px+502][py+502]=-2; } d=0; while(m[x+502][y+502]==-1){ for(int i=2;i<=1002;i++){ for(int j=2;j<=1002;j++){ if(m[i][j]==d){ if(m[i][j+1]==-1)m[i][j+1]=d+1; if(m[i][j-1]==-1)m[i][j-1]=d+1; if(m[i+1][j]==-1)m[i+1][j]=d+1; if(m[i-1][j]==-1)m[i-1][j]=d+1; } } } d++; } cout<<d; }