POJ-3984-迷宫问题
Time Limit: 1000MS Memory Limit: 65536K
Description
定义一个二维数组:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
题目链接:POJ-3984
题目大意:给出迷宫的图,1不能走,0能走,输出从(0,0)点到(4,4)点的最短路径
题目思路:经典BFS,详见代码
以下是代码:
//
// K.cpp
// 搜索
//
// Created by pro on 16/3/21.
// Copyright (c) 2016年 pro. All rights reserved.
//
#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <cstring>
#include <algorithm>
#include <string>
#include <set>
#include <functional>
#include <numeric>
#include <sstream>
#include <stack>
#include <map>
#include <queue>
#include<iomanip>
using namespace std;
int g[6][6];
int vis[6][6];
struct node
{
int r,c;
};
queue<node> que;
int dx[4] = {0,0,-1,1};
int dy[4] = {-1,1,0,0};
int cnt = 0;
int d[10][10]; // 记录是第几层
node father[10][10]; //记录该节点的父节点
vector <node> nodes; //记录路径
void printf_ans(node u)
{
while(1)
{
nodes.push_back(u);
if (d[u.r][u.c] == 0) break; //头结点
u = father[u.r][u.c]; //找出对应的父节点
}
for (int i = (int)nodes.size() - 1; i >= 0; i--)
{
printf("(%d, %d)\n",nodes[i].r,nodes[i].c);
}
}
void bfs()
{
node zero;
zero.r = 0;
zero.c = 0;
d[0][0] = 0;
vis[0][0] = 1;
que.push(zero);
while(!que.empty())
{
node front = que.front();
que.pop();
if (front.r == 4 && front.c == 4)
{
printf_ans(front);
return;
}
for(int i = 0; i < 4; i++)
{
int x = front.r + dx[i];
int y = front.c + dy[i];
node v;
v.r = x;
v.c = y;
if (x >= 0 && x < 5 && y >= 0 && y < 5 && g[x][y] == 0 && !vis[x][y])
{
d[v.r][v.c] = d[front.r][front.c] + 1;//记录层数
father[v.r][v.c] = front;//记录该节点的父节点
vis[x][y] = 1;
que.push(v);
}
}
}
}
int main()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
cin >> g[i][j];
}
}
bfs();
}