题解:U631666 爱丽丝逃离城镇(escape)

· · 算法·理论

前言,U631666 的题解

题目描述

爱丽丝在一个 h*w 的城镇里,可以按任意顺序重复执行以下两种操作:

$2$:选择一个上下左右方向,推倒障碍。 当爱丽丝推倒障碍时,可以将当前区域在该方向上前 $1$ 格 和前 $2$ 格 区域(如果它们是障碍)变为道路。 注意:即使前 $1$ 格或前 $2$ 格位于城镇外,仍然可以进行推倒操作,但城镇外的区域不会发生变化。 爱丽丝最初位于区域 $(A,B)$,想要到达位于区域 $(C,D)$ 的出口,逃离城镇。 请计算爱丽丝到达出口所需的最小推倒次数。 # 算法思路 通过题目可知,这道题用搜索或 dp 来做,但是 dp 需要从四个方向走,是方格取数加强版,难度太大,暂不考虑。 搜索的话,通过时间,深搜肯定是会超时,所以用广搜,但是怎么搜索呢? 首先我们想到,可以搜索起点或终点,来判断这些点的最优解,但是这样可能会出现非最优解的问题,如果强行最优解的话,时间肯定是过不了的。 我们可以把这道题看作连通块问题,通过可以把和起点连接的点设为 $1$,表示可以用 $0$ 次推动走到,然后用 bfs,把这些点入队,以此把这些点可以进行一次推动可以到达的地方设为 $1$,以此类推就可以了。 # 代码部分 ```cpp #include<bits/stdc++.h> #define int long long #define MAX 0x3f3f3f3f3f3f3f3f #define MIN -0x3f3f3f3f3f3f3f3f #define endl "\n" using namespace std; const int dx [] = { -1 , 0 , 1 , 0 } , dy [] = { 0 , 1 , 0 , -1 }; int h , w , dis [ 1010 ] [ 1010 ] , a , b , c , d; char ch [ 1010 ] [ 1010 ]; int bfs () { memset ( dis , 0x3f , sizeof ( dis ) ); //初始化 dis [ a ] [ b ] = 0; deque < pair < int , int > > q; q . push_back ( make_pair ( a , b ) ); //将起点初始化 while ( !q . empty () ) { int x = q . front () . first , y = q . front () . second; q . pop_front (); if ( x == c && y == d ) //如果到达,返回 { return dis [ x ] [ y ]; } for ( int i = 0 ; i < 4 ; i++ ) { int nx = x + dx [ i ] , ny = y + dy [ i ]; if ( nx >= 1 && nx <= h && ny >= 1 && ny <= w && ch [ nx ] [ ny ] == '.' && dis [ nx ] [ ny ] > dis [ x ] [ y ] ) //判断是否满足条件 { dis [ nx ] [ ny ] = dis [ x ] [ y ]; q . push_front ( make_pair ( nx , ny ) ); //继续搜索 } } for ( int i = 0 ; i < 4 ; i++ ) //进行推一次 { for ( int j = 1 ; j <= 2 ; j++ ) { int nx = x + dx [ i ] * j , ny = y + dy [ i ] * j; if ( nx >= 1 && nx <= h && ny >= 1 && ny <= w && ch [ nx ] [ ny ] == '#' && dis [ nx ] [ ny ] > dis [ x ] [ y ] + 1 ) //进行判断 { dis [ nx ] [ ny ] = dis [ x ] [ y ] + 1; q . push_back ( make_pair ( nx , ny ) ); } } } } return dis [ c ] [ d ]; //最后的返回 } signed main() { ios_base :: sync_with_stdio ( 0 ); cin . tie ( nullptr ); cout . tie ( nullptr ); cin >> h >> w; for ( int i = 1 ; i <= h ; i++ ) { for ( int j = 1 ; j <= w ; j++ ) { cin >> ch [ i ] [ j ]; } } cin >> a >> b >> c >> d; cout << bfs (); // bfs 算法 return 0; } ```