回 帖 发 新 帖 刷新版面

主题:[原创]迷宫程序

发一个迷宫程序,只要建立一个迷宫的数据文件,用TXT建,但要以.c格式保存,如mazedata.c
内容可自定,如###########  #   # ##  #   # ##    ## ### ###  # ##   #    ## #   # ### ####  #####   # #####      ###########


但迷宫周围要有一圈墙,数[color=FF0000]据间不能有回车等任何东西[/color],所以数据就像上面的样子其实是这样:
##########
#  #   # #
#  #   # #
#    ## ##
# ###  # #
#   #    #
# #   # ##
# ####  ##
###   # ##
###      #
##########
运行一下就有结果了,*是通路,@是回溯的路径,迷宫数据是可自定的。



回复列表 (共12个回复)

沙发

#define OK            1
#define FAILE         0
#define ERROR         0
#define UP            0
#define RIGHT         1
#define DOWN          2
#define LEFT          3
#define MAZE_MAX_WID  100
#define    MAZE_MAX_LEN  100

#include <iostream>
using namespace std;

typedef struct Coordinate {
    int row;             /*行*/
    int col;             /*列*/
}Coordinate;

typedef struct Maze {
    int maze_len;        /*迷宫长度*/
    int maze_wid;        /*迷宫宽度*/
    char value[MAZE_MAX_WID][MAZE_MAX_LEN];
                         /*每个位置由有'\254','*','@',' '四个值*/
                         /*分别表示'墙','通路','回溯过的路径'和'为走过的路径'*/
}Maze,*MazeP;

typedef int Direction;   /*方向,有UP(0),RIGHT(1),DOWN(2),LEFT(3)四个值*/



int main()
{
    Maze maze;
    MazeP mp=&maze;
    FILE *fp;
    Coordinate entry,export;

    int init_maze(MazeP mp,FILE *fp);
    int maze_path_search(MazeP mp,Coordinate entry,Coordinate export);
    int print_maze_path(MazeP mp);

    /*输入迷宫宽和长*/
    printf("set the size of maze with width and length.\ninput two number.\n");
    scanf("%d%d",&maze.maze_wid,&maze.maze_len);
    while((maze.maze_wid < 1) || (maze.maze_wid > MAZE_MAX_WID) || (maze.maze_len < 1) || (maze.maze_len > MAZE_MAX_LEN)) {
        printf("the width or length is illegle.input them again");
        scanf("%d%d",&maze.maze_wid,&maze.maze_len);
    }

    /*输入起点*/
    printf("input two coordinates of entry.\n");
    scanf("%d%d",&entry.row,&entry.col);
    while((entry.row < 0) || (entry.row > maze.maze_wid) || (entry.col < 0) || (entry.col > maze.maze_len)) {
        printf("the entry is illegle.input two coordinates again");
        scanf("%d%d",&entry.row,&entry.col);
    }


    /*输入终点*/
    printf("input two coordinates of export.\n");
    scanf("%d%d",&export.row,&export.col);
    while((export.row < 0) || (export.row > maze.maze_wid) || (export.col < 0) || (export.col > maze.maze_len)) {
        printf("the export is illegle.input two coordinates again");
        scanf("%d%d",&export.row,&export.col);
    }

    if((fp = fopen("MazeData.c","r")) == NULL) {   /*文件打不开*/
        printf("cannot open this file.\n");
        exit(0);
    }

    init_maze(mp,fp);                               /*初始化迷宫*/
    printf("this is the maze.\n");
    print_maze_path(mp);                            /*输出迷宫*/
    printf("\n");
    maze_path_search(mp,entry,export);   /*搜索路径并输出*/
    
    fclose(fp);
    return 0;
}

板凳

int init_maze(MazeP mp,FILE *fp)
{
    int i,j;
    char ch;

    if(mp == NULL)                                  /*迷宫不存在*/
        return ERROR;


    for(i = 0; i < mp->maze_wid; i++) {             /*读取迷宫数据*/
        for(j = 0; j < mp->maze_len; j++) {
            fscanf(fp,"%c",&ch);
            if(ch == EOF) {                         /*文件中的数据不够*/
                return ERROR;
            }
            mp->value[i][j] = ch;
        }
    }

    return OK;
}

int maze_path_search(MazeP mp,Coordinate entry,Coordinate export)
{
    Coordinate next_path;
    Direction dire;
    char (*p)[MAZE_MAX_LEN];
    Coordinate locate_next_path(Coordinate post_path,int dire);
    int print_maze_path(MazeP mp);

    p = mp->value;
    p[entry.row][entry.col] = '*';

    if((entry.row == export.row) && ((entry.col == export.col))){/*入口就是出口*/
        print_maze_path(mp);
        printf("\n");
        return OK;
    }
    else {
        for(dire = UP; dire <= LEFT; dire++) {                  /*依次向四个方向探索*/
            next_path = locate_next_path(entry,dire);           /*取下个位置的坐标*/
            if(p[next_path.row][next_path.col] == ' ') {        /*下个位置未走过*/
                if( (maze_path_search(mp,next_path,export)) == FAILE)          /*以下个位置为入口继续*/
                p[next_path.row][next_path.col] = '@';
            }
        }
    }
    return FAILE;
}

Coordinate locate_next_path(Coordinate post_path,int dire)
{/*取下个位置的坐标*/
    int row,col;
    Coordinate next_path;
    row = post_path.row;
    col = post_path.col;

    switch(dire) {
    case UP:    row--;break;
    case RIGHT: col++;break;
    case DOWN:  row++;break;
    case LEFT:  col--;break;
    default:    break;
    }

    next_path.row = row;
    next_path.col = col;

    return next_path;
}

int print_maze_path(MazeP mp)
{
    int i,j;
    int length,width;

    length = mp->maze_len;
    width = mp->maze_wid;

    for(i = 0; i < width; i++) {
        for(j = 0; j < length; j++) {
            printf("%c",mp->value[i][j]);
        }
        printf("\n");
    }
    return OK;
}


3 楼

前段时间,论坛的一个兄弟写的一个迷宫程序,给你参考一下!

#include<iostream>
#include<ctime>
#include<stack>
#include<windows.h>
using namespace std;

const int East  = 0;
const int South = 1;
const int West  = 2;
const int North = 3;
const int pause = 50; //老鼠走一步需要的毫秒数

class MouseMaze
{
public:
    MouseMaze(int h, int w);
    ~MouseMaze();
    void display()const;
    bool hasCrossOver();
private:
    const int row;
    const int col;
    char **p;
    void Init();
};

MouseMaze::MouseMaze(int h,int w):row(h),col(w)
{
    p=new char *[row];
    for(int i=0;i<row;++i)
        p[i]=new char[col];
    Init();
}

MouseMaze::~MouseMaze()
{
    for(int i=0;i<row;i++)
        delete []p[i];
    delete []p;
}


void MouseMaze::display()const
{
    for(int i=0;i<row;++i)
    {
        for(int j=0;j<col;++j)
            cout<<p[i][j];
        cout<<endl;
    }
}

void MouseMaze::Init() //随机生成迷宫
{
    srand(time(0));
    for(int i=0;i<row;++i)
    {
        for(int j=0;j<col;++j)
        {
            if((i==0)||(j==0)||(i==row-1)||(j==col-1))
            {
                p[i][j]='*';
                continue;
            }
            if(rand()%100<80)
                p[i][j]=' ';
            else
                p[i][j]='O';
        }
    }
    p[1][1]='Z';
}

4 楼

bool MouseMaze::hasCrossOver()
{
    int   flag, i=1,j=1;
    stack<int> s;
    while(true)
    {
        if(i==row-2&&j==col-2)
        {
            int m, n;
            stack<int> newStack;
            while(!s.empty())
            {
                newStack.push(s.top());
                s.pop();
            }
            for(m=0;m<row;++m)
            {
                for(n=0;n<col;++n)
                    if(p[m][n] == 'Z')
                        p[m][n] = ' ';
            }
            m = 1;
            n = 1;
            p[m][n]='Z';
            while(!newStack.empty())
            {
                flag=newStack.top();
                switch(flag)
                {
                    case East:
                        ++n; break;
                    case South:
                        ++m; break;
                    case West:
                        --n; break;
                    case North:
                        --m; break;
                }
                p[m][n] = 'Z';
                Sleep(pause);
                system("cls");
                display();
                newStack.pop();
            }
            return true;
        }//end if;

    //    case East:
        if((j+1<col-1)&&(p[i][j+1]==' '))
        {
            p[i][++j] = 'Z';
            s.push(East);
        }

    //    case South:
        else if((i+1 < row-1) && (p[i+1][j] == ' '))
        {
            p[++i][j] = 'Z';
            s.push(South);
        }

    //    case West:
        else if((j-1 > 0) && (p[i][j-1] == ' '))
        {
            p[i][--j] = 'Z';
            s.push(West);
        }

    //    case North:
        else if((i-1 > 0) && (p[i-1][j] == ' '))
        {
            p[--i][j] = 'Z';
            s.push(North);
        }

        else
        {
            if(s.empty()) return false;
            flag = s.top();
            s.pop();
            switch (flag)
            {
                case East:
                    --j; break;
                case South:
                    --i; break;
                case West:
                    ++j; break;
                case North:
                    ++i; break;
            }
        }
    }
}

int main()
{
    MouseMaze gMaze(20,79); //迷宫高20, 宽79
    gMaze.display();
    system("pause");
    if (gMaze.hasCrossOver())
        cout << "\n哈哈,老鼠成功逃出迷宫了~~~~" << endl;
    else
        cout << "\n可怜的老鼠,这辈子别想逃走!!!" << endl;
    system("pause");
}

5 楼

不错,看看去。

6 楼

其实可以不回溯求出解,用回溯法完全是试探的过程,也求不出最佳解(如果有多条通路,怎样求最短的呢?)

7 楼

哦,那不用回溯怎么解呢?
说说看好吗?

8 楼

回溯就是深度优先搜索(dfs),不能保证第一个解是最优解。
广度优先搜索(bfs),可以保证找到的第一个解最优。
另外可以用A*速度快但不能保证最优,A*结构上和广度优先相似,但它按权优先展开当前最优的结点。

知道了这些名词可以去google了,祝你找得痛快~

9 楼

果然看不懂 ,学习学习

10 楼

[quote]前段时间,论坛的一个兄弟写的一个迷宫程序,给你参考一下!

我看过这个程序了,编的非常好,学习。
祝大家新春快乐!!!

我来回复

您尚未登录,请登录后再回复。点此登录或注册