您的位置:首页 > 其它

NYoj 58 最少步数

2014-04-04 16:21 183 查看
广搜,尽量自己写队列!StL除了节省写代码的时间,其他的不见得节省多少!

题目来源:http://acm.nyist.net/JudgeOnline/problem.php?pid=58

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
using namespace std;
const int INF = 100000;

int Graph[9][9] = {
{1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,1,0,1},
{1,0,0,1,1,0,0,0,1},
{1,0,1,0,1,1,0,1,1},
{1,0,0,0,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1}
};

struct Point_State
{
int x;
int y;
int time;
Point_State()
{
x = 0;
y = 0;
time = INF;
}
};

int dir[4][2] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
Point_State Targetpos;
bool visit[9][9];

bool Is_CanGo(int x, int y)
{
if(x < 0 || x >= 9 || y < 0 || y >= 9 || Graph[x][y] == 1 || visit[x][y])
return false;
return true;
}

int BFS(Point_State CurState)
{
Point_State Que[100];
int qe, qs;
qe = qs = 0;
Que[qe++] = CurState;

while(qs < qe)
{
Point_State temp = Que[qs++];
if(temp.x == Targetpos.x && temp.y == Targetpos.y)
return temp.time;

visit[temp.x][temp.y] = 1;

for(int i = 0; i < 4; ++i)
{
Point_State t;
t.x = temp.x + dir[i][0];
t.y = temp.y + dir[i][1];

if(Is_CanGo(t.x, t.y) && t.time > temp.time + 1)
{
t.time = temp.time + 1;
Que[qe++] = t;
}
}
}
}

/**
用StL
//并不节省内存!
int BFS(Point_State Curpos)
{
queue <Point_State> Que;
while(!Que.empty())
Que.pop();
Que.push( Curpos );
while(!Que.empty())
{
Point_State temp = Que.front();
Que.pop();
if(temp.x == Targetpos.x && temp.y == Targetpos.y)
return temp.time;
visit[temp.x][temp.y] = 1;
for(int i = 0; i < 4; ++i)
{
Point_State t;
t.x = temp.x + dir[i][0];
t.y = temp.y + dir[i][1];
if(Is_CanGo(t.x, t.y) && t.time > temp.time + 1)
{
t.time = temp.time + 1;
Que.push(t);
}
}
}
return 0;
}
*/
int main()
{
int T;
scanf("%d", &T);
Point_State StartPos;
while(T--)
{
scanf("%d %d %d %d", &StartPos.x, &StartPos.y, &Targetpos.x, &Targetpos.y);
memset(visit, 0, sizeof(visit));
StartPos.time = 0;
printf("%d\n", BFS(StartPos));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: