这两天因为刚辞职,在家里闲来无事,就写了一个连连看的程序.写这个程序的时候,我发现用数据结构里面的迷宫问题来解决路径问题是很有效的.
这里,我就把查找路径的代码发给大家看看阿,其实就是数据结构里的迷宫算法,呵呵.(代码也许有错,没有仔细测试过)
代码如下:
BOOL CChildView::FindPath( int i1, int j1, int i2, int j2 )
{
int i = -1,j = -1,k = -1,dir = -1;
int top = -1;
BOOL bfind = FALSE;
/*---------------------------------------------------*/
查找路径( 从 <i1,j1> 到 <i2,j2> )
这里用栈来实现的,你当然也可以用其他方法了,呵呵
/*---------------------------------------------------*/
//<i1,j1>入栈
top = top + 1;
k = m_LLK.llk_map.map_bmp[i1][j1];
m_LLK.llk_path[top].i = i1;
m_LLK.llk_path[top].j = j1;
m_LLK.llk_path[top].dir = -1;
while ( top > -1 )
{
i = m_LLK.llk_path[top].i;
j = m_LLK.llk_path[top].j;
dir = m_LLK.llk_path[top].dir;
//如果找到
if ( (j == j2 && abs(i - i2) == 1) || ( i == i2 && abs(j - j2) == 1 ) )
{
bfind = TRUE; break;
}
//选择查找路径
bfind = FALSE;
while( dir < 4 && !bfind )
{
int i3 = -1,j3 = -1;
dir = dir + 1;
//查找方向
switch( dir )
{
case 0://向上
i3 = m_LLK.llk_path[top].i - 1;
j3 = m_LLK.llk_path[top].j;
break;
case 1://向右
i3 = m_LLK.llk_path[top].i;
j3 = m_LLK.llk_path[top].j + 1;
break;
case 2://向下
i3 = m_LLK.llk_path[top].i + 1;
j3 = m_LLK.llk_path[top].j;
break;
case 3://向左
i3 = m_LLK.llk_path[top].i;
j3 = m_LLK.llk_path[top].j - 1;
break;
}
if ( i3 < 0 || j3 < 0 )
{//如果没路,换一个方向继续找
continue;
}
else
{
i = i3; j = j3;
if ( m_LLK.llk_map.map_bmp[i][j] == -1 )
{//有路,且可走
bfind = TRUE;
break;
}
}
}
if ( bfind )
{//如果有路径可走,进栈,继续找路
m_LLK.llk_path[top].dir = dir;
top = top + 1;
m_LLK.llk_path[top].i = i;
m_LLK.llk_path[top].j = j;
m_LLK.llk_path[top].dir = -1;
m_LLK.llk_map.map_bmp[i][j] = -2;
}
else
{//无路则退栈,换路走
m_LLK.llk_map.map_bmp[m_LLK.llk_path[top].i][m_LLK.llk_path[top].j] = -1;
top = top - 1;
}
}
/*--------------------------*/
恢复走过的路径的初始值
/*--------------------------*/
for ( ; top >= 0; top-- )
{
m_LLK.llk_map.map_bmp[m_LLK.llk_path[top].i][m_LLK.llk_path[top].j] = -1;
}
if ( !bfind )
{
m_LLK.llk_map.map_bmp[i1][j1] = k;
}
return bfind;//返回TRUE表示找到
}