Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python (BFS) #586

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Binary file not shown.
Binary file not shown.
Empty file.
Binary file added .vs/AlgoBook/v17/.wsuo
Binary file not shown.
Binary file added .vs/AlgoBook/v17/Browse.VC.db
Binary file not shown.
3 changes: 3 additions & 0 deletions .vs/ProjectSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"CurrentProjectSetting": "No Configurations"
}
9 changes: 9 additions & 0 deletions .vs/VSWorkspaceState.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"ExpandedNodes": [
"",
"\\python",
"\\python\\graph_algorithms"
],
"SelectedNode": "\\python\\graph_algorithms\\breath_first_search_algorithm.py",
"PreviewInSolutionExplorer": false
}
Binary file added .vs/slnx.sqlite
Binary file not shown.
39 changes: 39 additions & 0 deletions python/graph_algorithms/breath_first_search_algorithm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from collections import defaultdict, deque

class Graph:
def __init__(self):
self.graph = defaultdict(list)

def add_edge(self, u, v):
# Add an edge from vertex u to vertex v
self.graph[u].append(v)

def bfs(self, start_vertex):
visited = set() # Set to keep track of visited vertices
queue = deque() # Queue for BFS traversal

visited.add(start_vertex) # Mark the start vertex as visited
queue.append(start_vertex) # Add the start vertex to the queue

while queue:
vertex = queue.popleft() # Get the next vertex from the queue
print(f"Visited vertex: {vertex}")

for neighbor in self.graph[vertex]:
if neighbor not in visited:
visited.add(neighbor) # Mark the neighbor as visited
queue.append(neighbor) # Add the neighbor to the queue

# Example usage and test
if __name__ == "__main__":
# Create a sample graph
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)

print("Breadth-First Traversal (starting from vertex 2):")
g.bfs(2)