DMOJ · tsoc16c1p4

Alex and Animal Rights

This C++ solution uses graph traversal for DMOJ tsoc16c1p4 Alex and Animal Rights. Read the reasoning, inspect the code, or try your own test case below.

tsoc16c1p4Graphs & treesGraph traversalC++40 lines
Solution009of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Graph traversal

Alex and Animal Rights matches counting four-connected non-wall enclosures that contain at least one M cell.

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

alex_and_animal_rights.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    vector<pair<int, int>> dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    void bfs(int i, int j, vector<vector<char>> &g, vector<vector<bool>> & vis){
        vis[i][j] = 1;
        queue<pair<int, int>> q;
        q.push({i, j});
        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 < g.size() && nc >= 0 && nc < g[0].size() && !vis[nr][nc] && g[nr][nc] != '#'){
                    q.push({nr, nc});
                    vis[nr][nc] = 1;
                }
            }
        }
    }
    int main(){
        ios::sync_with_stdio(0); cin.tie(0);
        int row, col; cin >> row >> col;
        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];
            }
        }
        int ans = 0;
        vector<vector<bool>> vis(row, vector<bool>(col));
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                if(!vis[i][j] && g[i][j] == 'M'){
                    bfs(i, j, g, vis);
                    ans++;
                }
            }
        }
        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.