• poj3984迷宫问题(DFS广搜)


    迷宫问题

    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)
     
    #include <iostream>
    #include <stdio.h>
    #include <string.h>
    #include <queue>
    using namespace std;
    bool ism[5][5];
    int a[5][5];
    int dx[4]={0, 1, 0, -1};
    int dy[4] = { 1, 0, -1, 0 };
    struct Node{
        int x;
        int y;
        int s;
        short l[30];
    };
    bool judge(int x, int y){
        if (x < 0 || x >= 5 || y < 0 || y >= 5)
            return true;
        if (ism[x][y])
            return true;
        if (a[x][y] == 1)
            return true;
        return false;
    }
    Node bfs(){
        queue<Node> q;
        Node cur, next;
        cur.x = 0;
        cur.y = 0;
        cur.s = 0;
        ism[cur.x][cur.y] = true;
        q.push(cur);
        while (!q.empty()){
            cur = q.front();
            q.pop();
            if (cur.x == 4 && cur.y == 4)
                return cur;
            int i, nx, ny;
            for (i = 0; i < 4; i++){
                nx = cur.x + dx[i];
                ny = cur.y + dy[i];
                if (judge(nx, ny))
                    continue;
                next = cur;
                next.x = nx;
                next.y = ny;
                next.s = cur.s+1;
                next.l[cur.s] = i;
                q.push(next);
            }
        }
        return cur;
    }
    int main(){
        int i, j;
        for (i = 0; i < 5; i++){
            for (j = 0; j < 5; j++){
                scanf("%d", &a[i][j]);
            }
        }
        memset(ism, 0, sizeof(ism));
        Node ans = bfs();
        int x, y;
        x = 0, y = 0;
        for (i = 0; i<= ans.s; i++){
            printf("(%d,%d)
    ", x, y);
            x += dx[ans.l[i]];
            y += dy[ans.l[i]];
        }
        return 0;
    }
    天晴了,起飞吧
  • 相关阅读:
    Java Executors小结
    Java取得一个对象里所有get方法和set方法, 读取某个类下所有变量的名称
    js中的this
    style,ng-style, ng-attr-style的对比
    keil 赋值之后再声明变量提示错误error: #268: declaration may not appear after executable statement in block
    网络字节顺序为大端模式
    MDK警告 warning: #111-D: statement is unreachable
    #231-D: declaration is not visible outside of function
    linux修改文件所有者和文件所在组
    getpwuid()
  • 原文地址:https://www.cnblogs.com/jianqiao123/p/10792186.html
Copyright © 2020-2023  润新知