思路
递归回溯
链表
头插
#include<iostream>
#include<cmath>
using namespace std;
#define m 3
#define n 4
struct Cnode//闭回上的路节点结构
{
int Ox;
int Oy;
Cnode * pPre;//指向前一个节点
};
struct Circle//闭回路链表结构
{
Cnode *Fakeh;//假的头指针,指向即将成为回路的链
Cnode *Rearh;//真的头指针,指向已经成为回路的链
};
int A[m][n]={{3,4,-1,-1},{-1,2,2,-1},{-1,-1,3,6}};//非负数表示数字格,-1表示空格
int x=1,y=3;//入基变量的坐标
Cnode cnode;//头结点
int mm=0;//标记下次遍历的起点坐标
Circle circle;//回路链表
void FindCircle(int x,int y);//传入入基变量坐标,找到它的闭回路
void z_hang(Circle circle,int w);//走行
void z_lie(Circle circle,int w);//走列
void FindCircle(int x,int y)
{
//初始化头节点
cnode.Ox=x;
cnode.Oy=y;
cnode.pPre=NULL;
//初始化回路链表
circle.Fakeh=&cnode;
circle.Rearh=NULL;
//先走行,在走行的函数里有走列函数
z_hang(circle,0);
return;
}
void z_hang(Circle circle,int w)
{
int kk=0;//有数字格的标记
for(int k=w;k<n&&k!=circle.Fakeh->Oy;k++)
{
if(A[circle.Fakeh->Ox][k]>=0)//遇到数字格
{
Cnode node;//创建一个节点
kk++;
node.Ox=circle.Fakeh->Ox;//新节点的横坐标
node.Oy=k;//新节点的纵坐标
node.pPre=circle.Fakeh;//头插,即让新节点长到链表上
circle.Fakeh=&node;//头指针指向新节点
if(circle.Fakeh->pPre!=NULL&&circle.Fakeh->Oy==y)//遇到和入基变量纵坐标相同的数字格,停止
{circle.Rearh=circle.Rearh;return;}//迭代结束,可用真头指针索引闭回路
z_lie(circle,0);//走列
break;
}
}
if(kk==0)//如果没有数字格
{
mm=circle.Fakeh->Ox+1;//上一节点走列,mm是列开始遍历的位置
circle.Fakeh=circle.Fakeh->pPre;//退回上一节点
z_lie(circle,mm);
}
return;
}
void z_lie(Circle circle,int w)
{
int kk=0;//有数字格的标记
for(int k=w;k<m&&k!=circle.Fakeh->Ox;k++)
{
if(A[k][circle.Fakeh->Oy]>=0)
{
Cnode node;
kk++;
node.Oy=circle.Fakeh->Oy;
node.Ox=k;
node.pPre=circle.Fakeh;
circle.Fakeh=&node;
z_hang(circle,0);
break;
}
}
if(kk==0)
{
mm=circle.Fakeh->Oy+1;
circle.Fakeh=circle.Fakeh->pPre;
z_hang(circle,mm);
}
return;
}
void main()
{
cout<<"找闭回路:"<<endl;
FindCircle(x,y);
cout<<circle.Rearh->Ox<<","<<circle.Rearh->Oy<<endl;
system("pause");
}
结果