Question

I am trying to write a program using a directed graph (which I know about but have never implemented) to simulate a network of transportation.

The user will input a planet name followed by an integer representing the number of total nodes in the graph. The user will then go through each node one by one. They will give it a name give the number of neighbors that node has and then the specific names. The input will look like this.

some_planet 4
node1 2 node2 node3
node2 1 node4
node3 1 node4
node4 1 node1

I then just output which nodes node1 cannot reach. However, I have some questions about implementing this.

1) The big one is storing this stuff. What is an easy way? I thinking about a LinkedList and thought I would link the locations. Then I could pop pointers onto them corresponding to whatever the input is. However, I have no idea how to do the last part.

2) The next big one is searching the graph. I was planning on a recursive depth-first-search . Is there anything wrong with this algorithm that you see? I need to search for every node individually this way though so I will have to increment this. Can I just throw everything in a for loop?

recursive-d-first-search(graph G, node start, node find)
  if(start == find)
    return true;

  else
    for every neighbor n of start
      success = recursive-d-first-search(graph G, node n, node find);
      if(success)
        return true;

  return false;
Was it helpful?

Solution

  1. I think you just need to use adjacency matrix to store whole graph's connection relation. in your case, it should be like:

        1    2    3    4
    
    1   0    1    1    0
    
    2   0    0    0    1
    
    3   0    0    0    1
    
    4   1    0    0    0
    
  2. If you use adjacency matrix, I think the breadth-first search may be a good choice, because it's easy to understand and implement. Meanwhile, you need one queue to store next nodes to be checked, and one list to store which nodes have already been checked

    For example, you want to check which nodes node1 cannot reach, you just check row 1 and see that it has 2 and 3, and put 2 and 3 to queue. Then check row 2 to see that it has 4, put 2 to list, and put 4 to queue. Then just use a for loop to do the same operation.

    In the end, you just need to check which nodes are not in list.

OTHER TIPS

You can also use Boost::Graph if you don't feel like reinventing the wheel...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top