?? main.cpp
字號(hào):
#include <stack>
#include <iostream>
using namespace std;
#define M 10
stack <int> stack1,stack2,stack3,stack4;
int move_up=1; //用于避免發(fā)生沿原路返回的往復(fù)運(yùn)動(dòng)
int move_down=1;
int move_right=1;
int move_left=1;
int way[M+2][M+2]= //對(duì)迷宮中的障礙進(jìn)行初始化
{{1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,1,1,1,1,1,0,0,0,0,1},
{1,0,0,0,0,0,1,0,1,0,0,1},
{1,0,0,0,1,0,1,0,0,0,0,1},
{1,0,1,0,1,0,1,0,1,1,0,1},
{1,0,1,0,1,0,1,0,1,0,0,1},
{1,0,1,1,1,0,1,0,1,0,1,1},
{1,0,1,0,0,0,1,0,1,0,1,1},
{1,0,1,0,1,1,1,0,1,0,0,1},
{1,1,0,0,0,0,0,0,1,0,0,1},
{1,0,0,0,0,1,1,1,1,0,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1}};
void judge(int line,int col) //按右、下、左、上的順序判斷可以向哪個(gè)方向走
{
if(!((line==M)&&(col==M))) //老鼠沒(méi)有到迷宮的出口時(shí)
{
if((way[line][col+1]==0)&&(move_right==1))//判斷是否可以向右走
{
col++; //可以向右走,則將列數(shù)加一
stack1.push(line); //將坐標(biāo)送入堆棧,stack1存放橫坐標(biāo),stack2存放列坐標(biāo)
stack2.push(col);
move_left=0; //此時(shí)不能向左返回,可以走其他三個(gè)方向
move_up=1;
move_down=1;
move_right=1;
judge(line,col); //在下一點(diǎn)繼續(xù)重復(fù)判斷
}
else
{
if((way[line+1][col]==0)&&(move_down==1)) //判斷是否可以向下走
{
line++; //可以向下走,則行數(shù)加一
stack1.push(line); //將坐標(biāo)送入堆棧
stack2.push(col);
move_up=0; //此時(shí)不能向上走,可以走其他三個(gè)方向
move_down=1;
move_left=1;
move_right=1;
judge(line,col);
}
else
{
if((way[line][col-1]==0)&&(move_left==1)) //判斷是否可以向左走
{
col--; //可以向左走,則列數(shù)減一
stack1.push(line); //將坐標(biāo)送入堆棧
stack2.push(col);
move_right=0; //此時(shí)不能向右走,可以走其他三個(gè)方向
move_up=1;
move_down=1;
move_left=1;
judge(line,col);
}
else
{
if((way[line-1][col]==0)&&(move_up==1)) //判斷是否可以向上走
{
line--; //可以向上走,則行數(shù)減一
stack1.push(line); //將坐標(biāo)送入堆棧
stack2.push(col);
move_down=0; //此時(shí)不能向下走,可以走其他三個(gè)方向
move_up=1;
move_right=1;
move_left=1;
judge(line,col);
}
else //四個(gè)方向都不能走時(shí)
{
line=stack1.top(); //保存上一次壓入堆棧的坐標(biāo)
col=stack2.top();
stack1.pop(); //將上一次壓入堆棧的坐標(biāo)pop出來(lái)
stack2.pop();
way[line][col]=1; //將這一點(diǎn)置為有障礙
line=stack1.top(); //回到前一點(diǎn)
col=stack2.top();
judge(line,col); //繼續(xù)判斷向哪個(gè)方向走
}
}
}
}
}
}
void print()
{
if(!((stack3.empty())||(stack4.empty()))) //將堆棧中的坐標(biāo)打印出來(lái)
{
int x=stack3.top();
int y=stack4.top();
stack3.pop();
stack4.pop();
cout<<x<<","<<y<<endl;
print();
}
}
void main()
{
cout<<"1,1"<<endl;
judge(1,1);
while(!(stack1.empty())) //將stack1中的橫坐標(biāo)壓入stack3
{ //使得橫坐標(biāo)能按路徑順序先后打印出來(lái)
int path1=stack1.top();
stack3.push(path1);
stack1.pop();
}
while(!(stack2.empty())) //將stack2中的縱坐標(biāo)壓入stack4
{ //使得縱坐標(biāo)能按路徑順序先后打印出來(lái)
int path2=stack2.top();
stack4.push(path2);
stack2.pop();
}
print(); //打印坐標(biāo)
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -