Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- constexpr char BARRIER = '#';
- int n, m;
- vector<vector<char>> board;
- vector<vector<int>> dis;
- constexpr int NR_DIRS = 4, dirI[] = {0, 0, 1, -1}, dirJ[] = {1, -1, 0, 0};
- unordered_map<int, int> fr;
- void read() {
- cin >> n >> m;
- board.resize(n + 3, vector<char>(m + 3, BARRIER));
- dis.resize(n + 3, vector<int>(m + 3, INT_MAX));
- for (int i = 1; i <= n; i++) {
- for (int j = 1; j <= m; j++) {
- cin >> board[i][j];
- }
- }
- }
- void lee() {
- queue<pair<int, int>> q;
- q.emplace(1, 1);
- dis[1][1] = 0;
- while (!q.empty()) {
- const auto &[i, j] = q.front();
- q.pop();
- for (int dir = 0; dir < NR_DIRS; dir++) {
- int newI = i + dirI[dir];
- int newJ = j + dirJ[dir];
- if (board[newI][newJ] != BARRIER && dis[newI][newJ] > dis[i][j] + 1) {
- dis[newI][newJ] = dis[i][j] + 1;
- q.emplace(newI, newJ);
- }
- }
- }
- }
- void cnt() {
- for (int i = 1; i <= n; i++) {
- for (int j = 1; j <= m; j++) {
- if ((i == 1 && j == 1) || (i == n && j == m) || board[i][j] == BARRIER) {
- continue;
- }
- fr[dis[i][j]]++;
- }
- }
- }
- void getAns() {
- int ans = INT_MAX;
- if (dis[n][m] == INT_MAX) {
- ans = 0;
- } else {
- for (const auto &it : fr) {
- ans = min(ans, it.second);
- }
- }
- cout << ans << endl;
- }
- signed main() {
- read();
- lee();
- cnt();
- getAns();
- return 0;
- }
Add Comment
Please, Sign In to add comment