DFS - find all paths where source is same as destination - c++

I want to find all the paths from source to destination using DFS where source is the same as the destination
E.g. Adjacency list for point A to B
0 - 1, 2
1 - 0, 3
2 - 0
3 - 1
So paths for 0 to 0 will be
0 1 0
0 2 0
0 1 3 1 0
Here is a working code that prints all the paths, but some are repeated and some are wrong.
#include <iostream>
#include <list>
#include <vector>
using namespace std;
// This class represents a directed graph using adjacency list representation
class Graph {
private:
// No. of vertices
int V;
// Pointer to an array containing adjacency lists
list<int> *adj;
// A function used by DFS
void DFSUtil(int v, int visited[], vector<int> &vec, int s, int d);
public:
// Constructor
Graph(int V);
// function to add an edge to graph
void addEdge(int v, int w);
// prints DFS traversal of the complete graph
void DFS();
};
Graph::Graph(int V) {
this->V = V;
this->adj = new list<int>[V];
}
void Graph::addEdge(int v, int w) {
// Add w to v’s list
adj[v].push_back(w);
adj[w].push_back(v);
}
Graph construct_graph() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(1, 3);
g.addEdge(0, 2);
return g;
}
void Graph::DFSUtil(int v, int visited[], vector<int> &paths, int s, int d) {
// Increase visited count of current node and add it to path
visited[v]++;
paths.push_back(v);
if((v == d) && (visited[s] == 2) && (paths.size() > 1)){
cout << "Path: ";
for(int i = 0; i < paths.size(); i++) {
cout << paths[i] << " ";
}
cout << endl;
} else {
// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for(i = adj[v].begin(); i != adj[v].end(); ++i) {
if(visited[*i] < 2) {
DFSUtil(*i, visited, paths, s, d);
}
}
}
if(paths.size() > 1) {
visited[v]--;
paths.pop_back();
}
}
// The function to do DFS traversal. It uses recursive DFSUtil()
void Graph::DFS() {
// Mark all the vertices as not visited
int *visited = new int[V];
for(int i = 0; i < V; i++) {
visited[i] = 0;
}
// store potential path here till destination is reached
vector<int> paths;
// Call the recursive helper function to print DFS traversal
// starting from all vertices one by one
for (int i = 0; i < V; i++) {
if (visited[i] < 2) {
DFSUtil(i, visited, paths, 0, 0);
}
}
}
int main() {
// construct graph
// 0 ----- 1
// | |
// | |
// 2 3
Graph g = construct_graph();
// Time: O(V + E), Space: O(V^2)
g.DFS();
cout << endl;
return 0;
}
This is my output:
Path: 0 1 0
Path: 0 1 3 1 0
Path: 0 2 0
Path: 0 1 0
Path: 0 1 3 1 0
Path: 0 2 0
Path: 0 3 1 0
Path: 0 3 1 3 1 0
This is what i am expecting:
Path: 0 1 0
Path: 0 1 3 1 0
Path: 0 2 0

Related

How can check u , v edges connect or not in DFS C++

input v = 4 , e =3
edges (1,2)
edges (3,2)
edges (3,1)
i want to check u = 3 , v = 1
out put : yes
and i want check u = 1 , v = 3
out put : no
have matrix
0 1 0 0
0 0 0 0
1 1 0 0
0 0 0 0
void DFS(int i,int t)
{
int j;
visited[i] = 1;
cout << i+1 << " ";
if(i == t)
cout << "yes";
for(j=0;j<V;j++)
{
if(G[i][j]==1 && visited[j] == 0)
DFS(j,t,x);
}
}
Normally a DFS implementation for something like this might look something like (I haven't tested it so there may be an issue or two):
bool dfs(int this_node, int destination_node) {
// base case where this node is the destination node
if (this_node == destination_node) return true;
// mark this node as visited
visited[this_node] = true;
// go deeper in the search
for (size_t next_node = 0; next_node < V; ++ next_node) {
// skip the search if this node isn't a valid child
if (visited[next_node] || !g[this_node][next_node]) {
continue;
}
// here is the recursive step
if (dfs(next_node, destination_node)) {
return true;
}
}
// if we made it all the way here, then the search failed to reach the destination
return false;
}
Then you'd be able to call this from the main function:
if (dfs(source_node, destination_node)) {
std::cout << "yes\n";
} else {
std::cout << "no\n";
}

Recursive function that uses static var

So this function seems to require the use of a static function, The problem I have realized is that there is no way to reset the static var before the recursive function ends. Is there a way to do it that I am not seeing or is there a good way to do this without the use of the static var.
The goal of this function is to fill an array with the odd var first, so say you call it fillAryOddFirst(ary, 13) then the array would be filled in the following order
[13, 11, 9, 7, 5, 3, 1, 2, 4, 6, 8, 12]
void fillAryOddFirst(int ary[], int size) {
static int pos;
if (size <= 0) {
return;
}
if(size % 2 != 0){
ary[pos] = size;
pos++;
}
fillAryOddFirst(ary, size-1);
if(size % 2 == 0 ){
ary[pos] = size;
pos++;
}
return;
}
No, there is no way to reset a local static variable.
If you want to be able to reset it, your only option is to make it a global variable, i.e. move its declaration outside the function.
Another possibility is to make it a parameter that you pass by reference :
void fillAryOddFirst(int ary[], int size, int &pos)
{
if (size <= 0)
{
return;
}
if (size % 2 != 0)
{
ary[pos] = size;
pos++;
}
fillAryOddFirst(ary, size - 1, pos);
if(size % 2 == 0 )
{
ary[pos] = size;
pos++;
}
}
void fillAryOddFirst(int ary[], int size)
{
int pos = 0;
fillAryOddFirst(ary, size, pos);
}
If size is odd, write the first element. If it is even, write the last element. In either case, recursively "focus" on the remaining subarray:
void fillAryOddFirst(int ary[], int size) {
if(size > 0) {
if(size % 2 == 1) {
// +---+---|...|---+
// | s | ? |???| ? |
// +---+---|...|---+
// ^ ary ^ ary + size
// ^ ary + 1 ^ (ary + 1) + (size - 1)
// \-----------/ focus on this range
ary[0] = size;
fillAryOddFirst(ary + 1, size - 1);
} else /*if(size % 2 == 0)*/ {
// +---|...|---+---+
// | ? |???| ? | s |
// +---|...|---+---+
// ^ ary ^ ary + size
// | ^ ary + (size - 1)
// \-----------/ focus on this range
ary[size - 1] = size;
fillAryOddFirst(ary, size - 1);
}
}
}
Written as a loop, that would be
void fillAryOddFirst(int ary[], int size) {
for(; size > 0; size--) {
if(size % 2 == 1) *ary++ = size;
else ary[size - 1] = size;
}
}
That is, you're iterating through size down through 1 and placing the odds at the start and the evens at the end.
"...is there a good way to do this without the use of the static var."
Yes. Wrap the function in a class.
In a class, the "static int pos" function variable can become a simple data attribute of the wrapper.
Below are several code samples.
1) The first is to demonstrate your issue is repeatable.
2) A simple class wrapper called class FillAryOddFirstClass_t. The function is very much the same as your original, but pos is not static.
3) A simple Functor wrapper, called class FillAryOddFirstFunctor_t. Functors have a simpler invocation.
4) Because you have declared this post as a C++ question, item 4 uses a vector instead of an array -- BUT note that the code uses the same class to run the recursion as item 2, FillAryOddFirstClass_t, which expects an array! The vector data resides in dynamic memory, and by specifying "&iVec[0]' (instead of ary), the address passed is the beginning element of the vector data in heap.
5) This is item 2 with extras. class FillAryOddFirstClass2_t is internally complicated with 2 report functions. The report functions build strings to display progress of the recursion / decursion execution.
#include <iostream>
using std::cout, std::endl; // c++17
#include <iomanip>
using std::setw;
#include <string>
using std::string, std::to_string;
#include <vector>
using std::vector;
// original - with static
void fillAryOddFirst ( int ary[], int size )
{
static int pos; // <<<<<<<<<<<<<<< static
if (size <= 0) { return; }
if(size % 2 != 0) { ary[pos] = size; pos++; }
fillAryOddFirst(ary, size-1);
if(size % 2 == 0 ) { ary[pos] = size; pos++; }
return;
}
// class wrapper
class FillAryOddFirstClass_t // UDT - user defined type
{
int pos; // <<<<<<<<<<<<<<< not static, a simple attribute
public:
FillAryOddFirstClass_t() : pos (0) { }
~FillAryOddFirstClass_t() = default;
void fillAryOddFirst ( int ary[], int indx )
{
if (indx <= 0) { return; }
if(indx % 2 != 0) { ary[pos] = indx; pos++; }
fillAryOddFirst(ary, indx-1);
if(indx % 2 == 0 ) { ary[pos] = indx; pos++; }
return;
}
};
// Functor wrapper
class FillAryOddFirstFunctor_t // UDT (user defined type)
{
int pos; // <<<<<<<<<<<<<<< not static
public:
// default ctor and dtor do nothing, cost nothing
void operator()( int ary[], int indx) // functor entry
{
pos = 0; // init
fillAryOddFirst(ary, indx);
return;
}
private:
void fillAryOddFirst( int ary[], int indx)
{
if (indx <= 0) { return; }
if(indx % 2 != 0) { ary[pos] = indx; pos++; }
fillAryOddFirst(ary, indx-1);
if(indx % 2 == 0 ) { ary[pos] = indx; pos++; }
return;
}
};
// class wrapper, with cout progress indicator
class FillAryOddFirstClass2_t // UDT
{
int pos; // <<<<<<<<<<<<<<< no static
size_t sz = 10;
public:
FillAryOddFirstClass2_t() : pos (0) { }
~FillAryOddFirstClass2_t() = default;
void fillAryOddFirst ( size_t rLvl, int ary[], int indx )
{
if (indx <= 0) {
cout << "\n\n" << setw(11) << " " << "recurse end - decurse begins\n";
return;
}
if(indx % 2 != 0) { ary[pos] = indx; pos++; }
cout << rprtR (rLvl, ary); // recurse report
fillAryOddFirst (rLvl+1, ary, indx-1);
cout << rprtD (rLvl, ary); // decurse report
if(indx % 2 == 0 ) { ary[pos] = indx; pos++; }
return;
}
// report recurse
string rprtR ( size_t rLvl, int ary[])
{
std::stringstream ssOut;
ssOut << "\n " << setw(4) << rLvl
<< " " << show(ary) << ' ';
return ssOut.str();
}
// report decurse
string rprtD ( size_t rLvl, int ary[])
{
std::stringstream ssOut;
ssOut << "\n " << setw(4) << rLvl
<< " " << show(ary) << '_';
return ssOut.str();
}
string show(int ary[])
{
std::stringstream ssOut;
for (uint i=0; i<(sz-1); ++i)
if (ary[i])
ssOut << " " << ary[i];
return ssOut.str();
}
}; // class FillAryOddFirstClass2_t
Below is main(), which illustrates how each 'fill' function is used:
int main()
{
const size_t sz = 9;
{
cout << "\n\n Test1: original (function with static int pos) \n";
int ary[sz]; // automatic memory array
init(&ary[0], sz); // function to fill ary with 0's
show(&ary[0], sz);
// this function uses static int pos
fillAryOddFirst (&ary[0], sz);
show(&ary[0], sz);
}
{
cout << "\n\n Test2: class wrapper (no static)\n";
int ary[sz];
init(&ary[0], sz);
show(&ary[0], sz);
{
FillAryOddFirstClass_t faofObj;
faofObj.fillAryOddFirst(&ary[0], sz);
}
show(&ary[0], sz);
}
{
cout << "\n\n Test3: Functor Wrapper (no static)\n";
int ary[sz]; init(&ary[0], sz);
show(&ary[0], sz);
// no static int pos
FillAryOddFirstFunctor_t()(&ary[0], sz);
show(&ary[0], sz);
}
{
cout << "\n\n Test4: class, uses vector, not array (no static)\n";
vector<int> iVec;
for (uint i=0; i<sz; ++i) iVec.push_back(0); // vector grows
show(&iVec[0], sz);
{
FillAryOddFirstClass_t faof;
faof.fillAryOddFirst(&iVec[0], sz);
}
show(&iVec[0], sz);
}
{
cout << "\n\n Test5: class2 (no static) with graphic\n";
vector<int> iVec;
for (uint i=0; i<sz; ++i) iVec.push_back(0); // vector grows
show(&iVec[0], sz);
{
cout << "\n rlvl";
FillAryOddFirstClass2_t faof2;
faof2.fillAryOddFirst(1, &iVec[0], sz);
cout << "\n rlvl";
}
cout << "\n\n ";
show(&iVec[0], sz);
}
cout << endl;
return 0;
}
Output:
Test1: original (function with static int pos)
0 0 0 0 0 0 0 0 0
9 7 5 3 1 2 4 6 8
Test2: class wrapper (no static)
0 0 0 0 0 0 0 0 0
9 7 5 3 1 2 4 6 8
Test3: Functor Wrapper (no static)
0 0 0 0 0 0 0 0 0
9 7 5 3 1 2 4 6 8
Test4: class, uses vector, not array (no static)
0 0 0 0 0 0 0 0 0
9 7 5 3 1 2 4 6 8
Test5: class2 (no static) with graphic
0 0 0 0 0 0 0 0 0
rlvl
1 9
2 9
3 9 7
4 9 7
5 9 7 5
6 9 7 5
7 9 7 5 3
8 9 7 5 3
9 9 7 5 3 1
recurse end - decurse begins
9 9 7 5 3 1_
8 9 7 5 3 1_
7 9 7 5 3 1 2_
6 9 7 5 3 1 2_
5 9 7 5 3 1 2 4_
4 9 7 5 3 1 2 4_
3 9 7 5 3 1 2 4 6_
2 9 7 5 3 1 2 4 6_
1 9 7 5 3 1 2 4 6 8_
rlvl
9 7 5 3 1 2 4 6 8

How to generate a permutation without two adjacent consecutive numbers?

In this problem, we will say that a permutation is cool is it does not have two adjacent consecutive numbers. Given n, print all the cool permutations of {0, …, n − 1}.
Input
input consists of several cases, each with an n between 1 and 9.
Output
For every case, print in lexicographical order all the cool permutations of {0, …, n − 1}.
I know how to solve the problem that prints all the permutations of { 1, …, n-1 } in lexicographical order. But I do not know how to generate the permutations without two adjacent consecutive numbers.
#include <iostream>
#include <vector>
using namespace std;
void write(const vector<int>& v) {
int s = v.size()-1;
for (int i = 0; i < s; ++i) cout << v[i] << ' ';
cout << v[s] << endl;
}
void generate(vector<int>& v, vector<bool>& u, int i, int n) {
if (i == n) write(v);
else {
for (int s = 1; s <= n; ++s) {
if (not u[s]) {
v[i] = s;
u[s] = true;
generate(v, u, i+1, n);
u[s] = false;
}
}
}
}
int main() {
int n;
while (cin >> n) {
vector<int> v(n);
vector<bool> u(n, false);
generate(v, u, 0, n-1);
cout << endl;
}
}
With this input:
1
2
3
4
5
I expect this output:
0
1 3 0 2
2 0 3 1
0 2 4 1 3
0 3 1 4 2
1 3 0 2 4
1 3 0 4 2
1 4 2 0 3
2 0 3 1 4
2 0 4 1 3
2 4 0 3 1
2 4 1 3 0
3 0 2 4 1
3 1 4 0 2
3 1 4 2 0
4 1 3 0 2
4 2 0 3 1
Thanks in advance!
An inefficient way of generating cool permutations, would be to first generate all permutations, and then to create a method that takes the vector v (who stores a candidate permutation), and evaluate whether this permutation is cool or not. If yes, print, if no, skip it, as #YSC suggested.
Example:
bool isCool(const vector<int>& v)
{
// special case, v.size==2
if(v.size() == 2) {
if(v[0] == v[1] + 1 || v[0] == v[1] - 1) {
return false;
} else {
return true;
}
}
// start from second element to pre-last
// and check if prev and next are adjacent to it
for(size_t i = 1; i < v.size() - 1; ++i) {
if(v[i] == v[i - 1] + 1 || v[i] == v[i - 1] - 1 ||
v[i] == v[i + 1] + 1 || v[i] == v[i + 1] - 1)
return false;
}
return true;
}
and then you would use it like in your generate method:
if (i == n && isCool(v)) write(v);
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
bool ConsecValues(int x, int y)
{
return abs(x - y) == 1;
}
bool HasConsecAdjValues(const vector<int>& v)
{
vector<int>::const_iterator cIter = adjacent_find(v.cbegin(), v.cend(),
ConsecValues);
return cIter != v.end();
}
vector<vector<int>> GetCoolPerms(int n)
{
vector<vector<int>> result;
vector<int> v(n);
iota(v.begin(), v.end(), 0);
do {
if (!HasConsecAdjValues(v))
result.push_back(v);
} while (std::next_permutation(v.begin(), v.end()));
return result;
}
void PrintPerm(const vector<int>& v)
{
for (const auto& num : v)
cout << num;
cout << endl;
}
int main()
{
vector<vector<int>> coolPerms = GetCoolPerms(5);
for (const auto& perm : coolPerms)
PrintPerm(perm);
getchar();
}

Duplicate data when printing the adjacency list of a graph

I was just trying to implement an adjacency list based graph, I'm not able to sort out, why second value appears twice in output print:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
int k = 0;
int n = 0;
cin>>k;
while(k>0){
cin>>n;
//Declare Adjacency List
vector<vector<pair<int, int>>> G;
G.resize(n);
//Add an edge u,v of weight w
while(n>0){
int u=0,v=0,w=0;
cin>>u>>v>>w;
G[u].push_back({v,w});
n--;
}
int i=0;
vector<vector<pair<int,int>>>::iterator it;
vector<pair<int,int>>::iterator it1;
for(it=G.begin() ; it < G.end(); it++,i++ ) {
for (it1=G[i].begin();it1<G[i].end();it1++){
for(pair<int,int> p: G[i]){
cout <<" "<<i<<"-> (w = "<<p.second<<") -> "<<p.first;
}
cout<<endl;
}
}
k--;
}
return 0;
}
Input:
1
5
1 2 2
2 3 1
2 4 4
4 5 3
Output:
0-> (w = 0) -> 0
1-> (w = 2) -> 2
2-> (w = 1) -> 3 2-> (w = 4) -> 4
2-> (w = 1) -> 3 2-> (w = 4) -> 4
4-> (w = 3) -> 5
I want to learn implementation.
Any new implementation will also be welcomed, I want to implement an undirected, weighted graph.
Because of your second for-loop
for (it1=G[i].begin();it1<G[i].end();it1++)
you get a duplicate output.
I assume you use C++11. Here's a slightly improved version of your program. First of all, I have added the option to read in the number of vertices and edges.
#include <iostream>
#include <utility>
#include <vector>
int main() {
int k = 0;
std::cin >> k;
while (k > 0) {
// read in number of nodes and edges
auto n = 0;
auto m = 0;
std::cin >> n >> m;
// Adjacency list
std::vector<std::vector<std::pair<int, int>>> G;
G.resize(n);
// Add an edge (u,v) with weight w
while (m > 0) {
int u=0, v=0, w=0;
std::cin >> u >> v >> w;
G[u].emplace_back(v,w);
--m;
}
// Print out adjacency list
for (auto i = 0; i < G.size(); ++i) {
for (const auto pair: G[i]) {
std::cout << " " << i << "-- (w = " << pair.second << ") --> " << pair.first;
}
std::cout << '\n';
}
--k;
}
return 0;
}
With your example-input
1
5
4
1 2 2
2 3 1
2 4 4
4 5 3
which denotes a graph with 5 vertices and 4 edges we get the following output:
1-- (w = 2) --> 2
2-- (w = 1) --> 3 2-- (w = 4) --> 4
4-- (w = 3) --> 5

Dijkstra's Algorithm , C++, Priority Queue, Adjacency List

#include <iostream>
#include <fstream>
#include <functional>
#include <climits>
#include <vector>
#include <queue>
#include <list>
using namespace std;
struct Vertices {
int vertex;
int weight;
Vertices(int v, int w) : vertex(v), weight(w) { };
Vertices() { }
};
class CompareGreater {
public:
bool const operator()(Vertices &nodeX, Vertices &nodeY) {
return (nodeX.weight > nodeY.weight) ;
}
};
vector< list<Vertices> > adj;
vector<int> weights;
priority_queue<Vertices, vector<Vertices>, CompareGreater> Q;
int nrVertices, nrEdges;
void Dijkstra(Vertices);
void makeGraph() {
ifstream myFile;
myFile.open("graph.txt");
myFile >> nrVertices >> nrEdges;
adj.resize(nrVertices+1);
int nodeX, nodeY, weight;
for (int i = 1; i <= nrVertices; ++i) {
weights.push_back(INT_MAX);
}
for (int i = 1; i <= nrEdges; ++i) {
myFile >> nodeX >> nodeY >> weight;
adj[nodeX].push_back(Vertices(nodeY, weight));
}
}
void printPath()
{
for (vector<int>::iterator itr = weights.begin()+1; itr != weights.end(); ++itr) {
cout << (*itr) << " "<<endl;
}
}
void Dijkstra(Vertices startNode) {
Vertices currVertex;
weights[startNode.vertex] = 0;
Q.push(startNode);
while (!Q.empty()) {
currVertex = Q.top();
Q.pop();
cout<<"Removed "<<&currVertex<<"from heap"<<endl;
if (currVertex.weight <= weights[currVertex.vertex]) {
for (list<Vertices>::iterator it = adj[currVertex.vertex].begin(); it != adj[currVertex.vertex].end(); ++it)
{
if (weights[it->vertex] > weights[currVertex.vertex] + it->weight) {
weights[it->vertex] = weights[currVertex.vertex] + it->weight;
Q.push(Vertices((it->vertex), weights[it->vertex]));
}
}
}
}
}
int main() {
makeGraph();
Dijkstra(Vertices(1, 0));
printPath();
return 0;
}
So this is my code to implement Dijkstra's algorithm with an adjacency list. With input:
7
2
2 2
4 1
2
4 3
5 10
2
1 4
6 5
4
3 2
5 2
6 8
7 4
1
7 6
0
1
6 1
This means that there exists 7 vertices in order from vertex 1 to 7. Vertex 1 has 2 edges, one to vertex 2 with weight 2, the second to vertex 4 with weight 1. Vertex 2 has 2 edges, the first to vertex 4 with weight 3, the second to vertex 5 with weight 10. Vertex 3 has 2 edges, the first to vertex 1 with weight 4, the second to vertex 6 with weight 5. And so forth.
However, it print out this:
Removed 0xbfb9d7a8from heap
Removed 0xbfb9d7a8from heap
0
4
2147483647
2147483647
2147483647
2147483647
When I need it to print out this:
V1: V2, 2; V4, 1
V2: v4, 3; V5, 10
V3: V1, 4; V6, 5
V4: V3, 2; V5, 2; V6, 8; V7, 4
V5: V7, 6
V6:
V7: V6, 1
Removed minimum 1 from heap
Print heap: V2, d=inf V4., d=inf v3, d= inf v7, d=inf v5......
Please help!!!!!