64,648
社区成员
发帖
与我相关
我的任务
分享
/**
* @Title 老鼠走迷宫
* @Author 孙琨
* @Date 2013-11-16
* @At XUST
* @All Copyright by 孙琨
*
*/
#include <iostream>
using namespace std;
int maze[7][7] = { // 初始化迷宫,英文maze为“迷宫”
{2,2,2,2,2,2,2},
{2,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,2,2}
};
int startI = 1,startJ = 1; // 入口行列坐标
int endI = 5,endJ = 5; // 出口行列坐标
int success = 0; // 判断路是否走通
int visit(int i,int j) // 自动搜寻路径
{
maze[i][j] = 1;
if((i == endI) && (j == endJ))
success = 1;
if((success != 1) && (maze[i][j+1] == 0)) // 下
visit(i,j+1);
if((success != 1) && (maze[i+1][j]) == 0) // 右
visit(i+1,j);
if((success != 1) && (maze[i][j-1] == 0)) // 上
visit(i,j-1);
if((success != 1) && (maze[i-1][j] == 0)) // 左
visit(i-1,j);
if(success != 1)
maze[i][j] = 0;
return success;
}
int main(void)
{
int i,j;
cout << "显示迷宫: " << 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) == 0)
{
cout << endl << "没有找到出口!" << endl;
}
else
{
cout << endl << "显示路径: " << endl;
for(i=0; i<7; i++)
{
for(j=0; j<7; j++)
{
if(maze[i][j] == 2)
cout << "■";
else if(maze[i][j] == 1)
cout << "♀";
else
cout << " ";
}
cout << endl;
}
}
return 0;
}
/**
* @Title 老鼠走迷宫的拓展探究
* @Author 孙琨
* @Date 2013-11-16
* @At XUST
* @All Copyright by 孙琨
*
*/
#include <iostream>
using namespace std;
int maze[9][9] = { // 初始化迷宫,英文maze为“迷宫”
{2,2,2,2,2,2,2,2,2},
{2,0,0,0,0,0,0,0,2},
{2,0,2,2,0,2,2,0,2},
{2,0,2,0,0,2,0,0,2},
{2,0,2,0,2,0,2,0,2},
{2,0,0,0,0,0,2,0,2},
{2,2,0,2,2,0,2,2,2},
{2,0,0,0,0,0,0,0,2},
{2,2,2,2,2,2,2,2,2}
};
int startI = 1,startJ = 1; // 入口行列坐标
int endI = 7,endJ = 7; // 出口行列坐标
void visit(int i,int j) // 自动搜寻路径
{
int m,n;
maze[i][j] = 1;
if((i == endI) && (j == endJ))
{
cout << endl << "显示路径:" << endl;
for(m=0; m<9; m++)
{
for(n=0; n<9; n++)
{
if(maze[m][n] == 2)
cout << "■";
else if(maze[m][n] == 1)
cout << "♀";
else
cout << " ";
}
cout << endl;
}
}
if(maze[i][j+1] == 0)
visit(i,j+1);
if(maze[i+1][j] == 0)
visit(i+1,j);
if(maze[i][j-1] == 0)
visit(i,j-1);
if(maze[i-1][j] == 0)
visit(i-1,j);
maze[i][j] = 0;
}
int main(void)
{
int i,j;
cout << "显示迷宫: " << endl;
for(i=0; i<9; i++)
{
for(j=0; j<9; j++)
{
if(maze[i][j] == 2)
cout << "■" ;
else
cout << " " ;
}
cout << endl;
}
visit(startI,startJ);
return 0;
}