zoukankan      html  css  js  c++  java
  • 队列的其本应用_迷官问题

    问题:
    利用队列的假出队,实现迷官问题寻解。
    要求:
    0 墙 1 路, 寻找最短路, 如果有多条,输出其中一条路。
    坐标系
    main.c

    #include <stdio.h>
    #include <stdlib.h>
    
    #define M 5
    int map[M+2][M+2];
    int front = 0, rear = 0;
    typedef struct Point_def{
        int x;
        int y;
        int pre;
    }Point;
    Point q[(M+2)*(M+2)];
    typedef struct direction_def{
        int x;
        int y;
    }Direction;
    Direction direct[4] = {
        {-1,0}, {0,1}, {1,0}, {0, -1}
    };
    int isEmpty(){
        return front==rear?1:0;
    }
    void initMap(){
        int i, j;
        for (i=0; i<M+2; i++)
            for (j=0; j<M+2; j++){
                if (i == 0 || i == M+1 || j == 0 || j == M+1){
                    map[i][j] = 0; continue;
                }
                scanf("%d", &map[i][j]);
            }
    }
    void enQueue(Point p){
        q[rear++] = p;
    }
    Point deQueue(){
        if (isEmpty()) 
            exit(1);
        return q[front++];
    }
    
    void findPath(int start_x, int start_y, int end_x, int end_y){
        int flag = 0;
        int d;
        int i, j;
        Point tmp_p1={start_x, start_y, -1};
        Point tmp_p2;
        enQueue(tmp_p1);
        while (!flag){
            tmp_p1 = deQueue();
            map[tmp_p1.x][tmp_p1.y] = -1;
            for (d=0; d<4; d++){
                i = tmp_p1.x + direct[d].x;
                j = tmp_p1.y + direct[d].y;
                if (map[i][j] == 1){
                    tmp_p2.x = i; tmp_p2.y = j; tmp_p2.pre = front-1;
                    enQueue(tmp_p2);
                }
                if (i == end_x && j == end_y){
                    tmp_p2.x = i; tmp_p2.y = j; tmp_p2.pre = front-1;
                    enQueue(tmp_p2);
                    flag = 1;  
                    break;
                }
    
            }// end for 
        }// end while 
    }// end findPath
    
    void printPath(){
        int k = rear-1;
        while (k != -1){
            printf("(%d,%d)
    ", q[k].x, q[k].y);
            k = q[k].pre;
        }
    }
    
    int main(){
        int flag = 0;
        int start_x = 1, start_y = 1;
        int end_x = 5, end_y = 5;
        initMap();
        findPath(start_x, start_y, end_x, end_y);
        printPath();
        return 0;
    }

    运行图1
    运行图2

  • 相关阅读:
    UART中RTS、CTS
    Verdi:内存不足
    SV学习之interface
    perl学习之:@_ $_
    perl学习之:package and module
    代码变成可执行程序期间,编译器做了那些事?
    perl学习之:use & require
    perl学习之:use and require
    8位二进制补码表示整数的最小值是什么,最大值是什么
    深入理解计算机系统
  • 原文地址:https://www.cnblogs.com/laohaozi/p/8266613.html
Copyright © 2011-2022 走看看