Jump to content

So here's my current code:

class Vertex:
    def __init__(self, name):
        self.name = name
        self.connections = {}

    def addNeighbour(self, neighbour, cost):
        self.connections[neighbour] = cost

class Graph:
    def __init__(self):
        self.vertexs = {}

    def addVertex(self, newVertex):
        new = Vertex(newVertex)
        self.vertexs[newVertex] = new

    def addEdge(self, src, dest, cost):
        self.vertexs[src].addNeighbour(self.vertexs[dest], cost)

    def dfs(self, start, end, visited, path):
        visited[start] = True
        path.append(start)
        if start == end:
            # End node found
            print("found")
        else:
            # Use depth first search
            for connection in graph.vertexs[start].connections:
                if visited[connection.name] == False:
                    self.dfs(connection.name, end, visited, path)
        return path

def setup():
    graphList = {
        0: [1, 2],
        1: [3],
        2: [1],
        3: [0, 2]
    }
    count = 0
    graph = Graph()

    for i in range(4):
        graph.addVertex(i)

    for arr in graphList.values():
        for i in range(len(arr)):
            graph.addEdge(count, arr[i], 1)
        count += 1
    return graph

graph = setup()

traversalResult = graph.dfs(0, 3, [False, False, False, False], [])

print(traversalResult)

It can find the target node with depth first search, however, once the node has been found, it will continue to loop for one more time since it hasn't searched node 3 from node 0.

 

How can I fix this so it just stops once the node has been found?

 

Many thanks!

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to comment
https://linustechtips.com/topic/1250831-python-depth-first-search-using-classes/
Share on other sites

Link to post
Share on other sites

You're not exiting the loop when you found something. If you're looping over 2 elements it's going to run the check on both elements even if one of them found something. This can be easily fixed by checking for return values: if the target has been found you should return the function and cause the parent function in the recursion to return as well.

    def dfs(self, start, end, visited):
        if start == end:
            # End node found
            print("found")
            return True
        else:
            # Use depth first search
            visited[start] = True
            for connection in graph.vertexs[start].connections:
                if visited[connection.name] == False:
                    if self.dfs(connection.name, end, visited):
                        return True
            return False

 

Don't ask to ask, just ask... please 🤨

sudo chmod -R 000 /*

Link to post
Share on other sites

40 minutes ago, Aspect11 said:

So here's my current code:

It can find the target node with depth first search, however, once the node has been found, it will continue to loop for one more time since it hasn't searched node 3 from node 0.

 

How can I fix this so it just stops once the node has been found?

 

Many thanks!

It looks like you're missing the stop condition for your recursive calls.

 

What I would do is add a return value to the dfs function that returns True when the node is found which I believe in your case is end. Every time you call dfs recursively, check if it returns True, if so, you can terminate immediately and skip any of the nodes that haven't been searched yet. And following the concept of recursion, that causes you to return True back up the chain so the program terminates.  

Intel® Core™ i7-12700 | GIGABYTE B660 AORUS MASTER DDR4 | Gigabyte Radeon™ RX 6650 XT Gaming OC | 32GB Corsair Vengeance® RGB Pro SL DDR4 | Samsung 990 Pro 1TB | WD Green 1.5TB | Windows 11 Pro | NZXT H510 Flow White
Sony MDR-V250 | GNT-500 | Logitech G610 Orion Brown | Logitech G402 | Samsung C27JG5 | ASUS ProArt PA238QR
iPhone 12 Mini (iOS 18.3) | iPhone 15 (iOS 18.3.1) | KZ AZ09 Pro x KZ ZSN Pro X | Sennheiser HD450bt
Intel® Core™ i7-1265U | Kioxia KBG50ZNV512G | 16GB DDR4 | Windows 11 Enterprise | HP EliteBook 650 G9
Intel® Core™ i5-8520U | WD Blue M.2 250GB | 1TB Seagate FireCuda | 16GB DDR4 | Windows 11 Home | ASUS Vivobook 15 
Intel® Core™ i7-3520M | GT 630M | 16 GB Corsair Vengeance® DDR3 |
Samsung 850 EVO 250GB | macOS Catalina | Lenovo IdeaPad P580

Link to post
Share on other sites

18 minutes ago, Sauron said:

You're not exiting the loop when you found something. If you're looping over 2 elements it's going to run the check on both elements even if one of them found something. This can be easily fixed by checking for return values: if the target has been found you should return the function and cause the parent function in the recursion to return as well.


    def dfs(self, start, end, visited):
        if start == end:
            # End node found
            print("found")
            return True
        else:
            # Use depth first search
            visited[start] = True
            for connection in graph.vertexs[start].connections:
                if visited[connection.name] == False:
                    if self.dfs(connection.name, end, visited):
                        return True
            return False

 

Thanks. I knew it was a simple solution, just didn't click with me. I'll try it out tomorrow.

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×