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

NYOJ58 最少步数(搜索)

2016-07-13 21:03 288 查看
描述

这有一个迷宫,有0~8行和0~8列:

 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

0表示道路,1表示墙。

现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?

(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)

输入第一行输入一个整数n(0<n<=100),表示有n组测试数据;

随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
输出输出最少走几步。
样例输入
2
3 1  5 7
3 1  6 7


样例输出
12
11

拉这个题主要是讨论一点问题。就是关于对于bfs做这个题标记与否,刚开始很容易进入一个误区,那就是和Red and Block 那个题一样,直接对输入的数组进行修改,但是里面存在一个很大的问题,那个题的数据是每运行一次输入一次数据,但是这个是只有一个矩阵,n次输入的结果都是从这一组数据中进行讨论,所以,这个题如果用bfs的话应该标记

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

struct data
{
int x;
int y;
int step;
} cur,pre;

int dis[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
int a[10][10] =
{
{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}
};
bool vis[10][10];
int sx,sy,ex,ey;

void bfs()
{
queue<data>que;
cur.x = sx;
cur.y = sy;
cur.step = 0;
que.push(cur);
vis[sx][sy] = 1;
while(!que.empty())
{
cur = que.front();
que.pop();

if(cur.x == ex && cur.y == ey)
{
cout << cur.step << endl;
return;
}

for(int i = 0;i < 4;i ++)
{
pre = cur;
pre.x = pre.x + dis[i][0];
pre.y = pre.y + dis[i][1];

if(pre.x >= 0 && pre.y >= 0 && pre.x < 9 && pre.y < 9 && !a[pre.x][pre.y] && !vis[pre.x][pre.y])
{
vis[pre.x][pre.y] = 1;
pre.step = pre.step + 1;

que.push(pre);
}
}
}
}

int main()
{
int t;
cin >> t;
while(t --)
{
memset(vis,0,sizeof(vis));
cin >> sx >> sy >> ex >> ey;
bfs();
}
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++