depth first search in an undirected, weighted graph using adjacency matrix?
<p>I don't want the answer, but I'm having trouble keeping track of the nodes. Meaning, say I have nodes 0, 1, 2, 3,4, 5, 6, 7, where 0 is start, and 7 is goal, I made an adjacency matrix like so: </p>

<pre><code>[
    [0, 3, 0, 0, 4, 0, 0, 0],
    [3, 0, 0, 0, 5, 0, 8, 0],
    [0, 0, 0, 4, 0, 5, 0, 0],
    [0, 0, 4, 0, 0, 0, 0, 14],
    [4, 5, 0, 0, 0, 2, 0, 0],
    [0, 0, 5, 0, 2, 0, 4, 0],
    [0, 8, 0, 5, 0, 4, 0, 0],
    [0, 0, 0, 14, 0, 0, 0, 0]
]
</code></pre>

<p>if it's a 0, there is no link between the nodes, otherwise, if it's greater than 1, then the number is the weight of the edge between those nodes.</p>

<p>I'm having trouble identifying what the actual node would be, versus a path.</p>

<p>I can find the goal, but I wouldn't know how to show the path to the goal, and what the total weight would be?</p>

<p>EDIT:
Here is what I am trying to achieve (this will not work, but this is the general idea):</p>

<pre><code>def dfs(graph, start, goal):
    stack = []
    visited = []

    stack.append(graph[start])
    visited.append(start)

    while (len(stack) != 0):
        current_node = stack.pop()
        if current_node not in visited:
            visited.append(current_node)

        if current_node = goal:
            return path
        else:
            for nodes in current_node:
                if nodes not in visited:
                    stack.append(nodes)
</code></pre>

<p>if the edges were unweighed this would be easier, but I'm basically adding all neighbors of the current node as long as I haven't visited it to the stack, until I find the goal node, and then I want to return the path. but in this case I know it's broken because 1) I'm not sure how to check if it's the goal node, since I'm only storing the nodes neighbors, and 2) not checking for the full path.</p>

<p>Maintain a <code>path variable</code> to store the vertex as u encounter them. When u found <code>end</code> vertex, the path variable will have the path. </p>

<p>Find the pseudo code for reference. Pardon any minor mistake in the code</p>

<pre><code>DFS (vertex start, vertex end, Graph G, list path):
         if(start==end):
              return TRUE
         for vertex in adjacent(start):
            if vertex not in path:     # has not been traversed
               path = path + [vertex]
               a = DFS(vertex, end, G, path)
               if a==TRUE:  # end vertex was found 
                  return TRUE
               path.delete(vertex)  # delete the vertex added,as its not in the path from start to end
</code></pre>

<p>Acc. to your code, when u found the goal vertex, the visited stack is contains the element in the path.         </p>

<p>I hope it helped. </p>

python algorithm search graph tree