Submission #1370286

#TimeUsernameProblemLanguageResultExecution timeMemory
1370286FaresSTHZoo (COCI19_zoo)C++20
110 / 110
25 ms5444 KiB
#include <bits/stdc++.h>
using namespace std;

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

int main() {
    // Optimize I/O operations
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int r, c;
    if (!(cin >> r >> c)) return 0;

    vector<string> g(r);
    for (int i = 0; i < r; i++) {
        cin >> g[i];
    }

    // dist array tracks the minimum "character changes" to reach each cell
    vector<vector<int>> dist(r, vector<int>(c, -1));
    deque<pair<int, int>> dq;

    // Start at top-left
    dq.push_back({0, 0});
    dist[0][0] = 1; // 1 represents the first animal

    int max_animals = 1;

    while (!dq.empty()) {
        auto [x, y] = dq.front();
        dq.pop_front();

        // Keep track of the maximum distance reached anywhere in the grid
        max_animals = max(max_animals, dist[x][y]);

        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];

            // Check bounds and ignore untouched snow
            if (nx >= 0 && nx < r && ny >= 0 && ny < c && g[nx][ny] != '*') {
                
                // 0 cost if same animal type, 1 cost if different
                int cost = (g[x][y] == g[nx][ny]) ? 0 : 1;

                // If unvisited or we found a cheaper path
                if (dist[nx][ny] == -1 || dist[x][y] + cost < dist[nx][ny]) {
                    dist[nx][ny] = dist[x][y] + cost;
                    
                    // 0-1 BFS logic: 0-weights to the front, 1-weights to the back
                    if (cost == 0) {
                        dq.push_front({nx, ny});
                    } else {
                        dq.push_back({nx, ny});
                    }
                }
            }
        }
    }

    cout << max_animals << "\n";
    return 0;
}
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...