码迷,mamicode.com
首页 > 其他好文 > 详细

POJ9384 迷宫问题(基础BFS)

时间:2014-07-22 14:16:04      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:算法   搜索   

本文出自:http://blog.csdn.net/svitter


题目:让你从(0, 0)走到(4,4),并且输出路径。输入数据:二位数组的迷宫;输出数据:路径;

题解:简单的BFS

注意:

1.去重;

2.墙不能走;

3.记录前一个节点


代码:

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

int maze[6][6];
bool visit[5][5];

struct node
{
    node *pre;
    int i;
    int j;
    node(){}
    node(int a, int b, node*c):i(a), j(b), pre(c){}
};

//1.去重
//2.是否墙壁
//
inline bool judge(int i, int j, int temp)
{
    if(temp < 0 || temp > 4)
        return false;

    //i, j 可以通行,并且没有访问过
    if(maze[i][j] != 1 && !visit[i][j])
        return true;

    return false;

}

void output(){}

int main()
{
    int i, j;
    for(i = 0; i < 5; i++)
        for(j = 0; j < 5; j++)
            scanf("%d", &maze[i][j]);

    node queue[1000];
    memset(visit, 0, sizeof(visit));

    int front , rear;
    front = rear = -1;
    node cur;
    int temp;
    queue[++rear] = node(4, 4, NULL);

    while(front != rear)
    {
        cur = queue[++front];
        i = cur.i;
        j = cur.j;
        if(i == 0 && j == 0)
            break;

        temp = cur.i+1;
        if(judge(temp, j, temp))
        {
            queue[++rear] = node(temp, j, &queue[front]);
            visit[temp][j] = 1;
        }

        temp = cur.j+1;
        if(judge(i, temp, temp))
        {
            queue[++rear] = node(i, temp, &queue[front]);
            visit[i][temp] = 1;
        }

        temp = cur.i-1;
        if(judge(temp, j, temp))
        {
            queue[++rear] = node(temp, j, &queue[front]);
            visit[temp][j] = 1;
        }

        temp = cur .j-1;
        if(judge(i, temp, temp))
        {
            queue[++rear] = node(i, temp, &queue[front]);
            visit[i][temp] = 1;
        }
    }

    node *tmp;
    tmp = &queue[front];

    while(tmp != NULL)
    {
        printf("(%d, %d)\n", tmp->i, tmp->j);
        tmp = tmp->pre;
    }
    return 0;
}


POJ9384 迷宫问题(基础BFS)

标签:算法   搜索   

原文地址:http://blog.csdn.net/svitter/article/details/38037865

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!