数据结构:DFS(入门)
数据结构课程刚讲过DFS用的还不熟练,但是数据结构太枯燥了,不想练;好巧不巧,CSDN上刚好有人问一道迷宫路径的问题;哎!瞬间起劲了,虽然啥都不懂,但是就是想写一下试试;扣了一个小时,不过还好写出来了,同时参考了《啊哈算法》第4章 第1节(不撞南墙不回头—深度优先搜索)
没有什么快乐是水题给不了的,如果有,那就多来几道;
#include< stdio. h>
#include< string. h>
#define N 1001
struct st{
int x;
int y;
} s[ N ] ;
int Map[ N ] [ N ] ;
int step[ N ] [ N ] ;
int flag[ N ] [ N ] ;
int next[ 4 ] [ 2 ] = { { 1 , 0 } , { 0 , 1 } , { - 1 , 0 } , { 0 , - 1 } } ;
int n, m, k= 1 , num= 1 ;
void input ( )
{
s[ 0 ] . x= s[ 0 ] . y= 1 ;
for ( int i= 0 ; i< k; i++ )
{
int x= s[ i] . x;
int y= s[ i] . y;
step[ x] [ y] = 1 ;
}
printf ( "%d\n" , num++ ) ;
for ( int i= 1 ; i<= n; i++ )
{
for ( int j= 1 ; j<= m; j++ )
{
char str1[ 5 ] = "->" ;
char str2[ 5 ] = "##" ;
if ( step[ i] [ j] == 1 )
printf ( "%4s" , str1) ;
else
printf ( "%4s" , str2) ;
}
printf ( "\n" ) ;
}
memset ( step, 0 , sizeof ( step) ) ;
}
void dsf ( int x, int y )
{
if ( x== n&& y== m)
{
input ( ) ;
return ;
}
int nx, ny;
for ( int i= 0 ; i< 4 ; i++ )
{
flag[ 1 ] [ 1 ] = 1 ;
nx= x+ next[ i] [ 0 ] ;
ny= y+ next[ i] [ 1 ] ;
if ( nx<= n&& ny<= m)
if ( flag[ nx] [ ny] == 0 && Map[ nx] [ ny] == 1 )
{
flag[ nx] [ ny] = 1 ;
s[ k] . x= nx;
s[ k++ ] . y= ny;
dsf ( nx, ny) ;
flag[ nx] [ ny] = 0 ;
k-- ;
}
}
}
int main ( )
{
memset ( Map, 0 , sizeof ( Map) ) ;
memset ( flag, 0 , sizeof ( flag) ) ;
scanf ( "%d%d" , & n, & m) ;
for ( int i= 1 ; i<= n; i++ )
{
for ( int j= 1 ; j<= m; j++ )
{
scanf ( "%d" , & Map[ i] [ j] ) ;
}
}
dsf ( 1 , 1 ) ;
return 0 ;
}