?? 深度優(yōu)先搜索.txt
字號(hào):
#include <iostream.h>
#include <memory.h>
#define SX 11 // 寬
#define SY 10 // 長(zhǎng)
int dx[4]={0,0,-1,1}; // 四種移動(dòng)方向?qū)和y坐標(biāo)的影響
int dy[4]={-1,1,0,0};
char Block[SY][SX] = // 障礙表
{{ 1,1,1,1,1,1,1,1,1,1,1 },
{ 1,0,1,0,1,0,0,0,0,0,1 },
{ 1,0,1,0,0,0,1,0,1,1,1 },
{ 1,0,0,0,1,0,1,0,0,0,1 },
{ 1,0,1,1,0,0,1,0,0,1,1 },
{ 1,0,1,0,1,1,0,1,0,0,1 },
{ 1,0,0,0,0,0,0,0,1,0,1 },
{ 1,0,1,0,1,0,1,0,1,0,1 },
{ 1,0,0,1,0,0,1,0,1,0,1 },
{ 1,1,1,1,1,1,1,1,1,1,1 }};
int MaxAct=4; // 移動(dòng)方向總數(shù)
char Table[SY][SX]; // 已到過(guò)標(biāo)記
int Level=-1; // 第幾步
int LevelComplete=0; // 這一步的搜索是否完成
int AllComplete=0; // 全部搜索是否完成
char Act[1000]; // 每一步的移動(dòng)方向,搜索1000步,夠了吧?
int x=1,y=1; // 現(xiàn)在的x和y坐標(biāo)
int TargetX=9,TargetY=8; // 目標(biāo)x和y坐標(biāo)
void Test( );
void Back( );
int ActOK( );
void main( )
{
memset(Act,0,sizeof(Act)); // 清零
memset(Table,0,sizeof(Table));
Table[y][x]=1; // 做已到過(guò)標(biāo)記
while (!AllComplete) // 是否全部搜索完
{
Level++;LevelComplete=+0; // 搜索下一步
while (!LevelComplete)
{
Act[Level]++; // 改變移動(dòng)方向
if (ActOK()) // 移動(dòng)方向是否合理
{
Test( ); // 測(cè)試是否已到目標(biāo)
LevelComplete=1; // 該步搜索完成
}
else
{
if (Act[Level]>MaxAct) // 已搜索完所有方向
Back( ); // 回上一步
if (Level<0) // 全部搜索完仍無(wú)結(jié)果
LevelComplete=AllComplete=1; //退出
}
}
}
}
void Test( )
{
if ((x==TargetX)&&(y==TargetY)) // 已到目標(biāo)
{
for (int i=0;i<=Level;i++)
cout<<(int)Act[i]; // 輸出結(jié)果
LevelComplete=AllComplete=1; // 完成搜索
}
}
int ActOK( )
{
int tx=x+dx[Act[Level]-1]; // 將到點(diǎn)的x坐標(biāo)
int ty=y+dy[Act[Level]-1]; // 將到點(diǎn)的y坐標(biāo)
if (Act[Level]>MaxAct) // 方向錯(cuò)誤?
return 0;
if ((tx>=SX)||(tx<0)) // x坐標(biāo)出界?
return 0;
if ((ty>=SY)||(ty<0)) // y坐標(biāo)出界?
return 0;
if (Table[ty][tx]==1) // 已到過(guò)?
return 0;
if (Block[ty][tx]==1) // 有障礙?
return 0;
x=tx;
y=ty; // 移動(dòng)
Table[y][x]=1; // 做已到過(guò)標(biāo)記
return 1;
}
void Back( )
{
x-=dx[Act[Level-1]-1];
y-=dy[Act[Level-1]-1]; // 退回原來(lái)的點(diǎn)
Table[y][x]=0; // 清除已到過(guò)標(biāo)記
Act[Level]=0; // 清除方向
Level--; // 回上一層
}
輸出結(jié)果中1代表上,2代表下,3代表左,4代表右。
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -