CS141 Lab 7

Check Connection Between Two Nodes


Graph Representation

The graph is represented with nodes and pointers. In each node, it has a unique ID, flag Visit and up to three pointers. The structure is showed as follows:

class node
{
public:

int ID;
bool Visit;
node *first, *second, *third;
}

1



In the class graph , we use an 1-D array nodelist to keep all the nodes. The total number of node N are read from a file. E.g. the above graph has N = 5.

class graph
{
public:
node *nodelist;

graph(int N)
{
nodelist = new node[N+1];
}

void AddEdge(int n1, int n2);
bool CheckConnect(node *node1, node *node2);
}


The function AddEdge( ) is reading a pair of number (n1, n2) from file, then adding the edge n1 -> n2 into the graph.
The function CheckConnect( ) is using DFS to find out whether there is a path from node1 to node2.


2
 


Input File Format

The input file has the following format: The first number N is total number of nodes. The second number V is total number of edges. Starting from the third line, a pair of numbers (n1, n2) each line represents the edge n1 -> n2. After V lines, there is a number T for the total number of tests, followed by a pairs of node (t1, t2) each line for checking the connection between t1 and t2.

5 // total number of nodes N
7 // total number of edges V
1     3
2     1
2     3
2     5
3     1
4     2
5     4
2 // total number of tests T
4     3
3     4


    File operations in C++:

    #include <fstream>  //include this head file

    ifstream infile("test1.txt");  //open a file for reading

    int num, num1, num2;
    infile >> num;  //read a integer from the file
    infile >> num1 >> num2;  // read two integers at the same time

    infile.close();  //close file before exit the program


Check Connection

Implement the CheckConnect( ) function using DFS. Output the result from CheckConnect(node1, node2). If there is a path from node1 to node2, then output "yes, node ## and node ## are connected.", else output "no, node ## and node ## are disconnected.".


Test Data

    test1.txt      test2.txt