Search
 
SCRIPT & CODE EXAMPLE
 

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;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: non stoichiometric nacl is yellow 
Cpp :: change int to string cpp 
Cpp :: for loop reverse C++ 
Cpp :: web scraping with cpp 
Cpp :: climits in cpp 
Cpp :: c++ throw exception 
Cpp :: set cmd size c++ 
Cpp :: stl for sorting in c++ 
Cpp :: border radius layout android xml 
Cpp :: write variable to file cpp 
Cpp :: how to remove spaces from a string 
Cpp :: c ++ program to search hashmap 
Cpp :: finding no of unique characters in a string c++ 
Cpp :: c++ find sum of vector 
Cpp :: C++ passing function arguments to a thread 
Cpp :: cout was not declared in this scope 
Cpp :: separating class into header and cpp file 
Cpp :: how to change string to lowercase and uperCase in c++ 
Cpp :: c++ fibonacci 
Cpp :: c++ string remove last character 
Cpp :: c++ evaluate expression 
Cpp :: c++ get time 
Cpp :: operands c++ 
Cpp :: C++ switch cases 
Cpp :: sin in c++ 
Cpp :: prime numbers less than a given number c++ 
Cpp :: c++ 2d vector assign value 
Cpp :: remove last index of the string in c++ 
Cpp :: create file c++ 
Cpp :: c++ print string 
ADD CONTENT
Topic
Content
Source link
Name
3+5 =