主题:一些有关递归回溯的程序
lanjingquan
[专家分:510] 发布于 2002-11-16 10:17:00
//
// road.cpp acm消防车题(91.A)
// lanjingquan 2002.7.20
///////////////////////////////////////////
#include"road.h"
ROAD::ROAD()
{
init();
times2=1;
record=new int[22];
}
bool ROAD::GetDataAndFind(char* file)
{
ifstream input(file,ios::nocreate);
int row,col;
while(!input.eof())
{
input>>goal;
input>>row>>col;
while(row!=0&&col!=0)
{
data[row][col]=1;
data[col][row]=1;
input>>row>>col;
}
FindRoad();
init();
}
return true;
}
bool ROAD::FindRoad(const int first,int& idx)
{
int n=idx;
record[n++]=first;
if(first==goal)
{
for(int j=0;j<idx;j++)
cout<<record[j]<<" ";
cout<<goal<<endl;
times++;
return true;
}
for(int i=1;i<=21;i++)
if(data[first][i]==1&&data[i][i]==0)
{
data[i][i]=1;
FindRoad(i,n);
data[i][i]=0;
}
return true;
}
bool ROAD::FindRoad()
{
cout<<"CASE# "<<(times2++)<<":"<<endl;
int i=0;
data[1][1]=1;
FindRoad(1,i);
cout<<"There are "<<times
<<" routes from the firestation to streetcorner "
<<goal<<"."<<endl<<endl;
return true;
}
bool ROAD::init()
{
for(int i=0;i<=21;i++)
for(int j=0;j<=21;j++)
data[i][j]=0;
goal=0;
times=0;
return true;
}
ROAD::~ROAD()
{
delete[] record;
}
5 楼
lanjingquan [专家分:510] 发布于 2002-11-16 10:21:00
//
// maze.cpp
// lanjingquan 2002.5.11
////////////////////////////////////////////////////
#include<iostream.h>
#include"stack.h"
struct items
{
int x;
int y;
int dir;//方向
};
ostream& operator<<(ostream& os,items& item)//输出函数
{
return os<<item.x<<","<<item.y<<","<<item.dir;
}
struct offset
{
int a; //x方向偏移
int b; //y方向偏移
};
enum directions{N,NE,E,SE,S,SW,W,NW};//方向
offset move[8]={{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}};//移动方向表
int maze[12][9]={{1,1,1,1,1,1,1,1,1},
{1,0,0,1,1,1,1,1,1},
{1,1,0,1,1,1,0,1,1},
{1,1,1,0,1,1,1,1,1},
{1,1,1,1,0,1,1,1,1},
{1,1,1,0,1,0,1,1,1},
{1,1,0,1,1,1,0,1,1},
{1,1,0,1,1,1,0,1,1},
{1,1,0,1,1,1,0,1,1},
{1,1,0,1,1,1,0,1,1},
{1,1,1,1,1,1,1,0,1},
{1,1,1,1,1,1,1,1,1}};
int mark[12][9]={0}; //记录数组
void path(int m,int p)
{
mark[1][1]=1; //入口
STACK<items> st; //记录栈
items tmp;//初始化
tmp.x=1;
tmp.y=1;
tmp.dir=E;
st.push(tmp);//进栈
while(!st.isEmpty())//非空,持续下去
{
tmp=st.pop();//退栈
int i=tmp.x;
int j=tmp.y;
int d=tmp.dir;//偏移表下标
while(d<8)//还有移动,继续移动
{
int g=i+move[d].a;//下一位置
int h=j+move[d].b;
if(g==m&&h==p)//出口
{
cout<<st;//输出
cout<<i<<" "<<j<<endl;
cout<<m<<" "<<p<<endl;
return;
}
if(!maze[g][h]&&!mark[g][h])//末到出口,下一位置
{
mark[g][h]=1;//标记为访问过
tmp.x=i;
tmp.y=j;
tmp.dir=d+1;
st.push(tmp);//进栈
i=g;//移动
j=h;
d=N;
}
else d++;//尝试下一方向
}
}
cout<<"no path in maze!"<<endl;
}
void main()
{
path(10,7);
}