64,654
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
using namespace std;
int maze[7][7]={{2,2,2,2,2,2,2},
{0,0,0,0,0,0,2},
{2,0,2,0,2,0,2},
{2,0,0,2,0,2,2},
{2,2,0,2,0,2,2},
{2,0,0,0,0,0,2},
{2,2,2,2,2,0,2}};
int startI=0;
int startJ=0;
int success=0;
int endI=5;
int endJ=5;
int visit(int i,int j)
{
maze[i][j]=0;
if(i==endI&&j==endJ)
{
success=1;
if(success!=1&&maze[i][j-1]==0)
visit(i,j-1);
else if(success!=1&&maze[i][j-1]==2)
visit(i,j);
if(success!=1&&maze[i-1][j]==0)
visit(i-1,j);
else if(success!=1&&maze[i][j-1]==2)
visit(i,j);
if(success!=1&&maze[i][j+1]==0)
visit(i,j+1);
else if(success!=1&&maze[i][j-1]==2)
visit(i,j);
if(success!=1&&maze[i+1][j]==0)
visit(i+1,j);
else if(success!=1&&maze[i][j-1]==2)
visit(i,j);
}
else if(success!=1)
maze[i][j]=0;
return success;
}
int main()
{
int i,j;
cout<<"print migong"<<endl;
for(i=0;i<7;i++)
{
for(j=0;j<7;j++)
if(maze[i][j]==2)
cout<<"黑框";
else
cout<<" ";
cout<<endl;
}
if(visit(startI,startJ))
cout<<"no outway"<<endl;
else
{
cout<<"Show pass"<<endl;
for(i=0;i<7;i++)
{
for(j=0;j<7;j++)
{
if(maze[i][j]==2)
cout<<"黑框";
else if(maze[i][j]==0)
cout<<"﹫";
else
cout<<" ";
}
cout<<endl;
}
}
return 0;
}
#include <stdio.h>
#define BOOL int
#define TRUE 1
#define FALSE 0
#define LINE 9
#define ROW 9
int maze[LINE][ROW] = { //构建一个9行9列迷宫
{2, 0, 2, 2, 2, 2, 2, 2, 2},
{0, 0, 2, 2, 2, 2, 0, 2, 2},
{2, 0, 0, 0, 0, 0, 0, 0, 2},
{2, 0, 2, 2, 0, 2, 2, 0, 2},
{0, 0, 2, 2, 0, 2, 2, 0, 2},
{2, 0, 2, 2, 0, 2, 2, 0, 2},
{2, 0, 2, 2, 0, 2, 0, 0, 0},
{2, 0, 2, 2, 0, 2, 2, 0, 0},
{2, 0, 2, 2, 0, 2, 2, 2, 2},
};
int start_x = 8, start_y = 1; //设置起点,start_x是行数
int end_x = 7, end_y = 8; //设置终点,end_x是行数
int Flag = FALSE; //初始探路标志为FALSE
BOOL Step(int x, int y); //探路函数
void Show(void); //显示迷宫的函数
int main(void)
{
printf("maze:\n"); //打印迷宫图,为方便查看,将数字换为图形打印
Show();
printf("\n");
if(Step(start_x, start_y))
{
printf("正确的走法如下!\n");
Show();
}
else
{
printf("没有发现出口!\n");
}
printf("\n");
return 0;
}
int Step(int x, int y) //用递归算法求解路径
{
maze[x][y] = 1;
//本位置是否是出口
if(x == end_x && y == end_y)
{
Flag = TRUE;
}
if(Flag != TRUE && maze[x + 1][y] == 0 && x<(LINE-1))
{Step(x + 1, y);}
if(Flag != TRUE && maze[x][y - 1] == 0 && y>0)
{Step(x, y - 1);}
if(Flag != TRUE && maze[x - 1][y] == 0 && x>0)
{Step(x - 1, y);}
if(Flag != TRUE && maze[x][y + 1] == 0 && y<(ROW-1))
{Step(x, y + 1);}
//如果没有成功,把现在的位置设置成0
if(Flag != TRUE)
{
maze[x][y] = 0;
}
return Flag;
}
void Show(void)
{
int x, y;
for(x = 0; x < LINE; x++)
{
for(y = 0; y < ROW; y++)
{
if(maze[x][y] == 2)
printf("■");
else if(maze[x][y] == 1)
printf("☆");
else
printf("□");
}
printf("\n");
}
return;
}
今天上午刚写的,正好用上了,嘿嘿