Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

how to know if two vertexes are connected in graph c++

#include <bits/stdc++.h>
using namespace std;
// We can use dfs alrogithm.
// in this example, we have an vector 'graph' in which indexes are connected 
// to each other, and an index of vertices we want to check if they are connected
// lets denote them as 'x' and 'y'
//NOTE THAT THIS ONLY WORKS ON NON-CYCLIC GRAPHS
bool dfs(int currIndx,int wantedIndx,vector<vector<int>> graph){
  	if(currIndx == wantedIndx)return true;
  	for(auto it : graph[currIndx]){
      if(dfs(it,wantedIndx,graph)) return true;
    }
  	return false;
}
int main(){
  // Create connections
  vector<int> Zero = {1,3};
  vector<int> One = {2};
  vector<int> Two = {4};
  vector<int> Three = {1};
  vector<int> Four = {0};
  // now add them all to one graph
  vector<vector<int>> graph(5);
  graph[0] = Zero;
  graph[1] = One;
  graph[2] = Two;
  graph[3] = Three;
  graph[4] = Four;
  // For this example lets check if 0 and 4 are somehow connected to each other
  bool answer = dfs(0,4,graph);
  if(answer == true)cout << "Yes, They Are Connected" << endl;
  else cout << "NO, They Are Not Connected ;(" << endl;
}
 
PREVIOUS NEXT
Tagged: #vertexes #connected #graph
ADD COMMENT
Topic
Name
8+8 =