您的位置:首页 > 编程语言 > C语言/C++

zoj 1148 The Game 一个晚上终于AC!

2015-04-23 22:38 686 查看
这题。。。一开始理解错了,以为一个格子就算一步,看样例里第二个输出是3以为答案错了、、、了解真相前又修修改改让输出和样例一样。参考了别人的思路才发现原来要输出的是线段数,而不是格子数。。。

总结一下要注意的地方:

1. 我前面说的,惨痛教训。。。。

2.他可以往边上出去一格,边缘要特别处理一下

3.用一个二维b数组记录是否已走过这个格子,防止走回头路

4.用广搜的时候要一条路走到头,这样才能实现同一条线段上是一样的步数

5.循环输入,每个输出要编号,每张图之间空一行

痛定思痛,理解题意是关键,仔细思考样例的图和输出,看看它到底是怎么算步数的。

#include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <vector>
#include <functional>
#include <queue>
using namespace std;

typedef struct
{
int x, y, step;
}block;

queue<block > q;

int main()
{
int w, h, board=1;
char a[80][80];
int b[80][80];
while(scanf("%d%d",&w,&h)&&w)
{

int pair=1;

getchar();
int i, j, x1,y1,x2,y2;
memset(a, 0, sizeof(a));
for(i=1; i<=h; i++)
{
for(j=1; j<=w; j++)
{
scanf("%c", &a[j][i]);
}
getchar();
}
printf("Board #%d:\n", board++);
block t, tt;
while(scanf("%d%d%d%d",&x1,&y1,&x2,&y2)&&x1)
{
memset(b, 0, sizeof(b));
while(!q.empty())
q.pop();
int flag=0;
t.x=x1;
t.y=y1;
t.step=0;
q.push(t);
while(!q.empty())
{
t=q.front();
if((t.x==x2&&t.y==y2) || (t.x==x2&&t.y==y2) || (t.x==x2&&t.y==y2) || (t.x==x2&&t.y==y2))
{
printf("Pair %d: %d segments.\n", pair++, t.step);
flag=1;
break;
}
q.pop();
if(t.x+1<=w+1&&(a[t.x+1][t.y]==' ' || a[t.x+1][t.y]==0) && !b[t.x+1][t.y] || (t.x+1==x2&&t.y==y2))
{
tt.x=t.x+1; tt.y=t.y; tt.step=t.step+1;
b[tt.x][tt.y]=1;
q.push(tt);
while(tt.x+1<=w+1&&(a[tt.x+1][tt.y]==' ' || a[tt.x+1][tt.y]==0) && !b[tt.x+1][tt.y] || (tt.x+1==x2&&tt.y==y2))
{
tt.x=tt.x+1;
b[tt.x][tt.y]=1;
q.push(tt);
}

}
if(t.x-1>=0&&(a[t.x-1][t.y]==' ' || a[t.x-1][t.y]==0) && !b[t.x-1][t.y] || (t.x-1==x2&&t.y==y2))
{
tt.x=t.x-1; tt.y=t.y; tt.step=t.step+1;
b[tt.x][tt.y]=1;
q.push(tt);
while(tt.x-1>=0&&(a[tt.x-1][tt.y]==' ' || a[tt.x-1][tt.y]==0) && !b[tt.x-1][tt.y] || (tt.x-1==x2&&tt.y==y2))
{
tt.x=tt.x-1;
b[tt.x][tt.y]=1;
q.push(tt);
}
}
if(t.y+1<=h+1&&(a[t.x][t.y+1]==' ' || a[t.x][t.y+1]==0) && !b[t.x][t.y+1] || (t.x==x2&&t.y+1==y2))
{
tt.x=t.x; tt.y=t.y+1; tt.step=t.step+1;
b[tt.x][tt.y]=1;
q.push(tt);
while(tt.y+1<=h+1&&(a[tt.x][tt.y+1]==' ' || a[tt.x][tt.y+1]==0) && !b[tt.x][tt.y+1] || (tt.x==x2&&tt.y+1==y2))
{
tt.y=tt.y+1;
b[tt.x][tt.y]=1;
q.push(tt);
}
}
if(t.y-1>=0&&(a[t.x][t.y-1]==' ' || a[t.x][t.y-1]==0) && !b[t.x][t.y-1] || (t.x==x2&&t.y-1==y2))
{
tt.x=t.x; tt.y=t.y-1; tt.step=t.step+1;
b[tt.x][tt.y]=1;
q.push(tt);
while(tt.y-1>=0&&(a[tt.x][tt.y-1]==' ' || a[tt.x][tt.y-1]==0) && !b[tt.x][tt.y-1] || (tt.x==x2&&tt.y-1==y2))
{
tt.y=tt.y-1;
b[tt.x][tt.y]=1;
q.push(tt);
}
}

}
if(!flag)
printf("Pair %d: impossible.\n", pair++);

}

printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ zoj 广搜