题目
思路
- bfs找到从起点到终点的最短路, +1(起点), 即为至少留下的白色块的个数
- 则答案 = 总白色块数 - (最短路+1)
代码
Code
// https://atcoder.jp/contests/abc088/tasks/abc088_d
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
using LL = long long;
using PII = pair<int, int>;
const int N = 55;
int dis[N][N];
char g[N][N];
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, 1, -1};
void solv()
{
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i ++) cin >> (g[i] + 1);
int cntw = 0;
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= m; j ++)
if (g[i][j] == '.') cntw ++;
if (g[1][1] == '#') {cout << -1; return; };
queue<PII> q;
q.push({1, 1}); dis[1][1] = 1;
while (q.size())
{
auto [x, y] = q.front(); q.pop();
for (int i = 0; i < 4; i ++)
{
int xx = x + dx[i], yy = y + dy[i];
if (xx < 1 || xx > n || yy < 1 || yy > m || dis[xx][yy] || g[xx][yy] == '#') continue;
dis[xx][yy] = dis[x][y] + 1;
q.push({xx, yy});
}
}
if (dis[n][m]) cout << cntw - dis[n][m] << endl;
else cout << -1 << endl;
}
int main()
{
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int T = 1;
// cin >> T;
while (T --)
{
solv();
}
return 0;
}