问题
代码实现
# include <stdio.h>
struct node {
int x;
int y;
int s;
} ;
int main ( ) {
struct node que[ 2501 ] ;
int i, j, startx, starty, q, p, head, tail, n, m, k, tx, ty, flog;
int a[ 50 ] [ 50 ] = { 0 } ;
int book[ 50 ] [ 50 ] = { 0 } ;
printf ( "请输入你要输入几行几列的迷宫:" ) ;
scanf_s ( "%d %d" , & n, & m) ;
printf ( "请输入你要输入的迷宫(0表示路,1表示障碍):" ) ;
for ( i= 1 ; i<= n; i++ )
for ( j = 1 ; j <= m; j++ ) {
scanf_s ( "%d" , & a[ i] [ j] ) ;
}
printf ( "请输入初始位置:" ) ;
scanf_s ( "%d %d" , & startx, & starty) ;
printf ( "请输入小哈的位置:" ) ;
scanf_s ( "%d %d" , & p, & q) ;
tail = 1 ;
head = 1 ;
que[ tail] . x = startx;
que[ tail] . y = starty;
que[ tail] . s = 0 ;
tail++ ;
book[ startx] [ starty] = 1 ;
flog = 0 ;
int next[ 4 ] [ 2 ] = { { 1 , 0 } ,
{ 0 , 1 } ,
{ - 1 , 0 } ,
{ 0 , - 1 } } ;
while ( head < tail) {
for ( k = 0 ; k <= 3 ; k++ ) {
tx = que[ head] . x + next[ k] [ 0 ] ;
ty = que[ head] . y + next[ k] [ 1 ] ;
if ( tx< 1 || tx> n || ty< 1 || ty> m) {
continue ;
}
if ( book[ tx] [ ty] == 0 && a[ tx] [ ty] == 0 ) {
book[ tx] [ ty] = 1 ;
que[ tail] . x = tx;
que[ tail] . y = ty;
que[ tail] . s = que[ head] . s + 1 ;
tail++ ;
}
if ( tx == p && ty == q) {
flog = 1 ;
break ;
}
}
if ( flog == 1 ) {
break ;
}
head++ ;
}
printf ( "最少要走%d步。" , que[ tail - 1 ] . s) ;
getchar ( ) ; getchar ( ) ;
return 0 ;
}
输入
5 4
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
1 1 4 3
输出
最少要走7 步。
输出
最少要走7 步。