二话不说 上迷宫代码!
#include <stdio.h>
#include <stdbool.h>
#define NUMBER 13
int fx[4] = { -1,1,0,0 };
int fy[4] = { 0,0,-1,1 };
void prin(char arr[][NUMBER]); //打印
bool work(char arr[][NUMBER],int x,int y); //判断是否可以走
bool mymap(char arr[][NUMBER], int x, int y); //迷宫走出去的算法
int main() {
char maze[NUMBER][NUMBER] = {
{"############"},
{"#...#......#"},
{"..#.#.####.#"},
{"###.#....#.#"},
{"#....###.#.#"},
{"####.#.#.#.#"},
{"####.#.#.#.."},
{"####.#.#.#.#"},
{"#........#.#"},
{"######.###.#"},
{"#......#...#"},
{"############"}
};
prin(maze);
/*迷宫起始坐标(2,0)*/
int x = 2;
int y = 0;
/*迷宫函数调用*/
mymap(maze, x, y);
prin(maze);
return 0;
}
//打印函数
void prin(char arr[][NUMBER]) {
//2个for循环打印
for (int i = 0 ; i < NUMBER ;i++)
{
for (int j = 0 ; j < NUMBER ; j++)
{
printf("%2c", arr[i][j]);
}
printf("\n");
}
}
bool work(char arr[][NUMBER], int x, int y) {
if (arr[x][y] != '#' && arr[x][y] != 'X' && x > 0 && y > 0 && x < NUMBER && y < NUMBER)
{
return true;
}
return false;
}
bool mymap(char arr[][NUMBER], int x, int y) {
if ( y >= NUMBER -2)
{
return true;
}
//方法
for (int i = 0; i < 4; i++)
{
int nextx = x + fx[i];
int nexty = y + fy[i];
if (work(arr, nextx, nexty))//判断是否可以走
{
arr[nextx][nexty] = 'X';
if (mymap(arr, nextx, nexty) == true)
{
return true;
}
}
}
arr[x][y] = '.';//回溯
return false;
}
效果: