01BFSが使える

ABC005 C 器物損壊!高橋君

問題概要

リンク参照

考察

  • 壁が来た時には壊して進むことが考えられるので今まで何回壁を壊したのかの情報を持っておきたい
  • なるべく壁を壊す回数を少なくして進む方がよさそう
  • 壁を壊して進むことは,コスト1の移動に相当し,壁以外を進む場合はコスト0の移動と考えると01BFSが使える
  • これを実装して投げたら通った(・∀・)

ソースコード

#include<iostream>
#include<vector>
#include<algorithm>
#include<cctype>
#include<utility>
#include<string>
#include<cmath>
#include<cstring>
#include<queue>
#include<map>
#include<set>
#include<climits>

#define REP(i, n) for(int i = 0;i < n;i++)
#define REPR(i, n) for(int i = n;i >= 0;i--)
#define FOR(i, m, n) for(int i = m;i < n;i++)
#define FORR(i, m, n) for(int i = m;i >= n;i--)
#define SORT(v, n) sort(v, v+n);
#define VSORT(v) sort(v.begin(), v.end());
#define llong long long
#define pb(a) push_back(a)

using namespace std;


typedef long long int ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;


template<typename T>
vector<T> make_v(size_t a) { return vector<T>(a); }
template<typename T, typename... Ts>
auto make_v(size_t a, Ts... ts) {
	return vector<decltype(make_v<T>(ts...))>(a, make_v<T>(ts...));
}
template<typename T, typename V>
typename enable_if<is_class<T>::value == 0>::type
fill_v(T& t, const V& v) { t = v; }
template<typename T, typename V>
typename enable_if<is_class<T>::value != 0>::type
fill_v(T& t, const V& v) {
	for (auto& e : t) fill_v(e, v);
}


#define ARRAY_MAX 100005
const int INF = INT32_MAX / 3;
const ll MOD = 1e9 + 7;

int dx[4] = { 1,0,0,-1 };
int dy[4] = { 0,1,-1,0 };


int ans[550][550];
char mp[550][550];
int h, w;
int sy, sx, gy, gx;

int main() {

	cin.tie(nullptr);
	ios::sync_with_stdio(false);

		

	for (int i = 0; i < 550; i++)
	{
		for (int j = 0; j < 550; j++)
		{
			ans[i][j] = INF;
		}
	}


	cin >> h >> w;


	for (int i = 0; i < h; i++)
	{
		for (int j = 0; j < w; j++)
		{
			cin >> mp[i][j];
			if (mp[i][j] == 's') {
				sy = i;
				sx = j;
			}
			if (mp[i][j] == 'g') {
				gy = i;
				gx = j;
			}
		}
	}

	

	deque<pii> que;

	que.push_back(pii(sy,sx));
	ans[sy][sx] = 0;

	while (!que.empty())
	{
		pii now = que.front();
		que.pop_front();
		
		for (int i = 0; i < 4; i++)
		{
			int ny = now.first + dy[i];
			int nx = now.second + dx[i];

			
			//範囲内
			int cost = 0;

			if (0 <= ny && ny < h && 0 <= nx && nx < w) {

				if (mp[ny][nx] == '#') {
					//壁なら破壊コストがいる
					cost = 1;
				}
				else
				{
					cost = 0;
				}

				//コストの更新

				if (ans[ny][nx] > ans[now.first][now.second] + cost) {
					ans[ny][nx] = ans[now.first][now.second] + cost;
					if (cost == 0) {
						que.push_front(pii(ny, nx));
					}
					else
					{
						que.push_back(pii(ny, nx));
					}

				}
			}
		}
	}


	if (ans[gy][gx] < 3) {
		cout << "YES" << endl;
	}
	else
	{
		cout << "NO" << endl;
	}
	
	return 0;
}