DMOJ · tree1

Is it a Tree?

This C++ solution uses graph traversal for DMOJ tree1 Is it a Tree?. Read the reasoning, inspect the code, or try your own test case below.

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

Approach

Graph traversal

Is It a Tree uses a fixed 4-by-4 adjacency matrix; the connectivity and edge-count checks match.

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

is_it_a_tree.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    int main(){
        int n = 4, m = 4, cnt = 0;
        vector<vector<int>> adj(n);
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                int x; cin >> x;
                if(x){
                    adj[i].push_back(j);
                    adj[j].push_back(i);
                    if(i < j) cnt++;
                }
            }
        }
        if(cnt != 3){
            cout << "No" << '\n';
             exit(0);
        }
        vector<bool> vis(n);
        queue<int> q;
        q.push(0); vis[0] = true;
        while(!q.empty()){
            int u = q.front(); q.pop();
            for(int v : adj[u]){
                if(!vis[v]){
                    vis[v] = true;
                    q.push(v);
                }
            }
        }
        bool good = 1;
        for(int i = 0; i < n; i++){
            if(!vis[i]) good = 0;
        }
        if(good) cout << "Yes" << '\n';
        else 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.