DMOJ · dmopc14c1p5

Surprise Teleport

This C++ solution uses breadth-first search for DMOJ dmopc14c1p5 Surprise Teleport. Read the reasoning, inspect the code, or try your own test case below.

dmopc14c1p5Graphs & treesBreadth-first searchC++44 lines
Solution208of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Breadth-first search

Surprise Teleport matches the grid, teleport locations, and shortest-time saving computed by BFS.

Graphs & trees

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

surprise_teleport.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    int main(){
        ios::sync_with_stdio(0); cin.tie(0);
        //idea is to use bfs to find shortest path without using teleport and then run bfs one more time with teleportion device taken into consideration
        int row, col; cin >> row >> col;
        int a, b; cin >> a >> b;
        int mr, mc; cin >> mr >> mc;
        vector<vector<char>> g(row, vector<char>(col));
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                cin >> g[i][j];
            }
        }
        vector<vector<int>> dist(row, vector<int>(col, INT_MAX));
        dist[a][b] = 0;
        queue<pair<int, int>> q;
        vector<pair<int, int>> dir = {{0, 1}, {-1, 0}, {1, 0}, {0, -1}};
        q.push({a, b});
        while(!q.empty()){
            auto[r, c] = q.front(); q.pop();
            for(auto[rr, cc] : dir){
                int nr = r + rr, nc = c + cc;
                if(nr >= 0 && nr < row && nc >= 0 && nc < col && g[nr][nc] != 'X' && dist[nr][nc] == INT_MAX){
                    dist[nr][nc] = dist[r][c] + 1;
                    q.push({nr, nc});
                }
            }
        }
        int distance = dist[mr][mc];
        int t; cin >> t;
        vector<pair<int, int>> tel;
        for(int i = 0; i < t; i++){
            int x, y; cin >> x >> y;
            tel.emplace_back(x, y);
        }
        int tel_dist = INT_MAX;
        for(auto[r, c] : tel){
            tel_dist = min(tel_dist, dist[r][c]);
        }
        int ans = distance - (tel_dist != INT_MAX ? tel_dist : distance);
        cout << ans << '\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.