HDU-1180-诡异的楼梯

题目链接

http://acm.hdu.edu.cn/showproblem.php?pid=1180

这个题目本身不是很难,就是分情况看‘|’和‘-’讨论方向而已,不过题目的意思要理解正确

即在碰到楼梯时已走了t步那么踩楼梯就应该是t+1步如果是‘|’那么if((t+1)%2==0)  则还是‘|’;否则是‘-’;

我在设置‘|’。‘-’时错了,害的我搞了很久才发现,做题应该先在草稿子上写好框架和主要程序,这样能减少程序的逻辑错误。

敲代码前多想想,多想几种思路,从中选最优的一种思路来敲。

代码:

#include<iostream>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<queue>
#include<algorithm>
using namespace std;

int ex,ey,n,m;
int dx[4]= {1,0,-1,0};
int dy[4]= {0,-1,0,1};
char map[30][30];
int vis[30][30];

struct node
{
int x,y,t;
};

queue<node> q;

void bfs(int stx,int sty)
{
memset(vis,0,sizeof(vis));
vis[stx][sty]=1;
node s,e;
while(q.size())
q.pop();
s.x=stx;
s.y=sty;
s.t=0;
q.push(s);
while(q.size())
{
s=q.front();
q.pop();
if(map[s.x][s.y]=='T')
{
printf("%d ",s.t);
break;
}
int i;
for(i=0; i<4; i++)
{
e.x=s.x+dx[i];
e.y=s.y+dy[i];
if(e.x>=0&&e.x<n&&e.y>=0&&e.y<m&&map[e.x][e.y]!='*')
{
int flag=0;
if(map[e.x][e.y]=='|')
{
if(s.t%2==0)
flag=1;
else
flag=2;
}
if(map[e.x][e.y]=='-')
{
if(s.t%2==0)
flag=2;
else
flag=1;
}
if(flag==1)
{
if(i%2==1)
{
e.t=s.t+1;
e.x=s.x;
e.y=s.y;
q.push(e);
}
else
{
e.x=e.x+dx[i];
e.y=e.y+dy[i];
if(e.x>=0&&e.x<n&&e.y>=0&&e.y<m&&map[e.x][e.y]!='*'&&vis[e.x][e.y]==0)
{
e.t=s.t+1;
q.push(e);
vis[e.x][e.y]=1;
vis[e.x-2*dx[i]][e.y]=1;
}
}
}
else if(flag==2)
{
if(i%2==0)
{
e.t=s.t+1;
e.x=s.x;
e.y=s.y;
q.push(e);
}
else
{
e.x=e.x+dx[i];
e.y=e.y+dy[i];
if(e.x>=0&&e.x<n&&e.y>=0&&e.y<m&&map[e.x][e.y]!='*'&&vis[e.x][e.y]==0)
{
e.t=s.t+1;
q.push(e);
vis[e.x][e.y]=1;
vis[e.x][e.y-2*dy[i]]=1;
}
}
}
else
{
if(vis[e.x][e.y]==0)
{
e.t=s.t+1;
q.push(e);
vis[e.x][e.y]=1;
}
}
}
}
}
}

int main(void)
{
int i,j,stx,sty;
while(scanf("%d%d",&n,&m)==2)
{
getchar();
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
{
scanf("%c",&map[i][j]);
if(map[i][j]=='S')
{
stx=i;
sty=j;
}
}
getchar();
}
bfs(stx,sty);
}
return 0;
}

原文地址:https://www.cnblogs.com/liudehao/p/4053980.html