bfs直接适合用在处理数据较少的的题目,如果数据量太大bfs处理不来。
BFS在求解最短路径或者最短步数上有很多的应用。
应用最多的是在走迷宫上。
现在这题的主要难点是在记录上一步的节点,不过这题的数据量比较小,
所以不用队列,用一维数组就好了。结构体内定义一个c变量来记录上一点。
struct eu{
int x;
int y;
int c;
} q[ 6 * 6 ] ;
也不用考虑,在转弯节点中的c会不会记录比较远的路径的上一点,因为路径短的比路径长优先遍历了,
此时的转弯节点已经被标记了,所以不用担心被路径长的节点再次访问。
下面我们看代码。
#include <queue>
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
int map[ 5 ] [ 5 ] , vis[ 5 ] [ 5 ] ;
int d[ 4 ] [ 2 ] = { { - 1 , 0 } , { 1 , 0 } , { 0 , - 1 } , { 0 , 1 } } ;
struct eu{
int x;
int y;
int c;
} q[ 6 * 6 ] ;
void print ( int head)
{
while ( q[ head] . c!= - 1 ) {
print ( q[ head] . c) ;
printf ( "(%d, %d)\n" , q[ head] . x, q[ head] . y) ;
return ;
}
printf ( "(0, 0)\n" ) ;
}
void bfs ( ) {
struct eu now;
int head= 0 ;
int tail= 1 ;
q[ head] . c= - 1 ;
q[ head] . x= q[ head] . y= 0 ;
vis[ 0 ] [ 0 ] = 1 ;
while ( head< tail) {
if ( q[ head] . x== 4 && q[ head] . y== 4 ) {
print ( head) ;
return ;
}
for ( int i= 0 ; i< 4 ; i++ ) {
now. x= q[ head] . x+ d[ i] [ 0 ] ;
now. y= q[ head] . y+ d[ i] [ 1 ] ;
now. c= head;
if ( now. x< 5 && now. y< 5 && now. x>= 0 && now. y>= 0 ) {
if ( ! vis[ now. x] [ now. y] && ! map[ now. x] [ now. y] ) {
vis[ now. x] [ now. y] = 1 ;
q[ tail] = now;
tail++ ;
}
}
}
head++ ;
}
}
int main ( ) {
memset ( vis, 0 , sizeof ( vis) ) ;
for ( int i= 0 ; i< 5 ; i++ ) {
for ( int j= 0 ; j< 5 ; j++ ) {
cin>> map[ i] [ j] ;
}
}
bfs ( ) ;
return 0 ;
}
```