DMOJ · ccc20s2

CCC 2020 S2 Escape Room

This C++ solution uses breadth-first search for CCC 2020 S2 Escape Room. Read the reasoning, inspect the code, or try your own test case below.

ccc20s2CCC 2020 S2Graphs & treesBreadth-first searchC++43 lines
Solution247of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Breadth-first search

The implementation follows the official CCC 2020 J5/S2 Escape Room rules: treat each cell as a state and reach every coordinate whose row-column product equals the current value.

Graphs & trees
Time
O(M × N)
Space
O(M × N)

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

Open official problem ↗View exact source file ↗
Implementation

CCC_2020_J5_S2_Escape_Room.cpp

C++

    #include <iostream>
    #include <queue>
    #include <vector>
    using namespace std;
     
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
     
        int rows, columns;
        if (!(cin >> rows)) return 0;
        cin >> columns;
     
        const int cellCount = rows * columns;
        vector<int> value(cellCount);
        vector<vector<int>> cellsByProduct(cellCount + 1);
     
        for (int row = 1; row <= rows; ++row) {
            for (int column = 1; column <= columns; ++column) {
                const int index = (row - 1) * columns + column - 1;
                cin >> value[index];
                cellsByProduct[row * column].push_back(index);
            }
        }
     
        queue<int> pending;
        vector<char> visited(cellCount, false);
        pending.push(0);
        visited[0] = true;
     
        while (!pending.empty()) {
            const int index = pending.front();
            pending.pop();
     
            if (index == cellCount - 1) {
                cout << "yes\n";
                return 0;
            }
     
            const int jumpValue = value[index];
            if (jumpValue > cellCount) continue;
     
            for (const int next : cellsByProduct[jumpValue]) {
                if (!visited[next]) {
                    visited[next] = true;
                    pending.push(next);
                }
            }
            cellsByProduct[jumpValue].clear();
        }
     
        cout << "no\n";
        return 0;
    }
     
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.