回溯法也称试探法,这种方法将问题的候选解按某种顺序逐一枚举和检验, 当发现当前的候选解, 不是解时, 就放弃它而选择下一个候选解, 如果当前的候选解, 除了不满足问题规模要求外, 其他所有要求都已满足, 则扩大当前候选解的规模, 继续试探. 如果当前候选解满足了包括问题在内的所有要求, 则这个候选解, 将成为问题的一个解.
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#pragma once
#define M 12
#define P 15
struct offsets
{
int a,b;
char *dir;
};
offsets move[8]={{-1,0,"N"},{-1,1,"NE"},{0,1,"E"},{1,1,"SE"},
{1,0,"S"},{1,-1,"SW"},{0,-1,"W"},{-1,-1,"NW"}};
int Maze[M+2][P+2]={
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{0,0,1,0,0,0,1,1,0,0,0,1,1,1,1,1,1},
{1,1,0,0,0,1,1,0,1,1,1,0,0,1,1,1,1},
{1,0,1,1,0,0,0,0,1,1,1,1,0,0,1,1,1},
{1,1,1,0,1,1,1,1,0,1,1,0,1,1,0,0,1},
{1,1,1,0,1,0,0,1,0,1,1,1,1,1,1,1,1},
{1,0,0,1,1,0,1,1,1,0,1,0,0,1,0,1,1},
{1,0,0,1,1,0,1,1,1,0,1,0,0,1,0,1,1},
{1,0,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1},
{1,0,0,1,1,0,1,1,0,1,1,1,1,1,0,1,1},
{1,1,1,0,0,0,1,1,0,1,1,0,0,0,0,0,1},
{1,0,0,1,1,1,1,1,0,0,0,1,1,1,1,0,1},
{1,0,1,0,0,1,1,1,1,1,0,1,1,1,1,0,0},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
};
int mark[M+2][P+2];
int SeekPath(int x,int y)
{
int i,g=0,h=0; char *d;
if(x==M&&y==P+1)
return 1;
for(i=0;i<8;i++)
{
g=x+move[i].a;
h=y+move[i].b;
d=move[i].dir;
if(Maze[g][h]==0&&mark[g][h]==0)
{
mark[g][h]=1;
if(SeekPath(g,h))
{
cout<<"("<<g<<","<<h<<"),"<<"Direction:"<<d<<","<<endl;
return 1;
}
}
}
if(x==1&&y==1)
cout<<"No path in the Maze"<<endl;
return 0;
}