I was torn between these two methods:
M1:
- Use adjacency list to represent graph G with vertices P and edges A
- Use DFS on G storing all the distances from p in an array d;
- Loop through d checking all entries. If some d[u] >6, return false otherwise true
M2:
- Use adjacency list to represent graph G with vertices P and edges A
- Use BFS on G storing all the distances from p in an array d;
- Loop through d checking all entries. If some d[u] >6, return false otherwise true
Both these methods will produce a worst case O(|P| + |A|)
, therefore I think that both would be a correct answer to this question. I had chosen the DFS method, with the reasoning that with DFS you should be able to find the "outlier" of freedom degree 7 earlier than with BFS, since with BFS you would have to traverse every single Vertex until degree 7 in every case.
Apparently this is wrong according to the teacher, as using DFS, you can't compute the distances. I don't understand why you wouldn't be able to compute the distances. I could have a number n
indicating the degree of freedom I am currently at. Starting from root p
, the child would have n = 1
. Now I store n
in array d
. Then I keep traversing down until no child is to be found, while incrementing n
and storing the value in my array d
. Then, if the back-tracking starts, the value n
will be decremented until we find an unvisited child node of any of the visited nodes on the stack. If there is an unvisited child, increment once again, then increment until no more child is found, decrement until the next unvisited child from the stack is found...
I believe that would be a way to store the distances with DFS