Advertisement
tepyotin2

The Number of Leaf Node

May 11th, 2025
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int n;
  6. string grid;
  7. vector<int> adj[1001];
  8. queue<int> q;
  9. vector<int> ans;
  10.  
  11. int main(){
  12.     //freopen("leafnodes.in", "r", stdin);
  13.    
  14.     cin >> n;
  15.     //adj.resize(n+1);
  16.     bool visited[n+1];
  17.     memset(visited, false, sizeof(visited));
  18.     for(int i=0; i<n; i++){
  19.         cin >> grid;
  20.         for(int j=0; j<n; j++){
  21.             if(grid[j] == '1'){
  22.                 adj[i+1].push_back(j+1);
  23.             }
  24.         }
  25.     }
  26.     q.push(1);
  27.     visited[1] = true;
  28.     while(!q.empty()){
  29.         int cur = q.front();
  30.         q.pop();
  31.         int count = 0;
  32.         for(auto v: adj[cur]){
  33.             if(!visited[v]){
  34.                 visited[v] = true;
  35.                 count++;
  36.                 q.push(v);
  37.             }
  38.         }
  39.         if(count == 0){
  40.             ans.push_back(cur);
  41.             //cout << s << cur;
  42.             //s = " ";
  43.         }
  44.     }
  45.     sort(ans.begin(), ans.end());
  46.     string s = "";
  47.     cout << ans.size() << '\n';
  48.     for(auto v: ans){
  49.         cout << s << v;
  50.         s = " ";
  51.     }
  52.     cout << '\n';
  53.    
  54.     return 0;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement