mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-07-18 18:14:34 +08:00
increment 1
This commit is contained in:
54
data_structures/graph/bellman_ford.py
Normal file
54
data_structures/graph/bellman_ford.py
Normal file
@ -0,0 +1,54 @@
|
||||
from __future__ import print_function
|
||||
|
||||
def printDist(dist, V):
|
||||
print("\nVertex Distance")
|
||||
for i in range(V):
|
||||
if dist[i] != float('inf') :
|
||||
print(i,"\t",int(dist[i]),end = "\t")
|
||||
else:
|
||||
print(i,"\t","INF",end="\t")
|
||||
print()
|
||||
|
||||
def BellmanFord(graph, V, E, src):
|
||||
mdist=[float('inf') for i in range(V)]
|
||||
mdist[src] = 0.0
|
||||
|
||||
for i in range(V-1):
|
||||
for j in range(V):
|
||||
u = graph[j]["src"]
|
||||
v = graph[j]["dst"]
|
||||
w = graph[j]["weight"]
|
||||
|
||||
if mdist[u] != float('inf') and mdist[u] + w < mdist[v]:
|
||||
mdist[v] = mdist[u] + w
|
||||
for j in range(V):
|
||||
u = graph[j]["src"]
|
||||
v = graph[j]["dst"]
|
||||
w = graph[j]["weight"]
|
||||
|
||||
if mdist[u] != float('inf') and mdist[u] + w < mdist[v]:
|
||||
print("Negative cycle found. Solution not possible.")
|
||||
return
|
||||
|
||||
printDist(mdist, V)
|
||||
|
||||
|
||||
|
||||
#MAIN
|
||||
V = int(raw_input("Enter number of vertices: "))
|
||||
E = int(raw_input("Enter number of edges: "))
|
||||
|
||||
graph = [dict() for j in range(E)]
|
||||
|
||||
for i in range(V):
|
||||
graph[i][i] = 0.0
|
||||
|
||||
for i in range(E):
|
||||
print("\nEdge ",i+1)
|
||||
src = int(raw_input("Enter source:"))
|
||||
dst = int(raw_input("Enter destination:"))
|
||||
weight = float(raw_input("Enter weight:"))
|
||||
graph[i] = {"src": src,"dst": dst, "weight": weight}
|
||||
|
||||
gsrc = int(raw_input("\nEnter shortest path source:"))
|
||||
BellmanFord(graph, V, E, gsrc)
|
67
data_structures/graph/breadth_first_search.py
Normal file
67
data_structures/graph/breadth_first_search.py
Normal file
@ -0,0 +1,67 @@
|
||||
#!/usr/bin/python
|
||||
# encoding=utf8
|
||||
|
||||
""" Author: OMKAR PATHAK """
|
||||
|
||||
from __future__ import print_function
|
||||
|
||||
|
||||
class Graph():
|
||||
def __init__(self):
|
||||
self.vertex = {}
|
||||
|
||||
# for printing the Graph vertexes
|
||||
def printGraph(self):
|
||||
for i in self.vertex.keys():
|
||||
print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]]))
|
||||
|
||||
# for adding the edge beween two vertexes
|
||||
def addEdge(self, fromVertex, toVertex):
|
||||
# check if vertex is already present,
|
||||
if fromVertex in self.vertex.keys():
|
||||
self.vertex[fromVertex].append(toVertex)
|
||||
else:
|
||||
# else make a new vertex
|
||||
self.vertex[fromVertex] = [toVertex]
|
||||
|
||||
def BFS(self, startVertex):
|
||||
# Take a list for stoting already visited vertexes
|
||||
visited = [False] * len(self.vertex)
|
||||
|
||||
# create a list to store all the vertexes for BFS
|
||||
queue = []
|
||||
|
||||
# mark the source node as visited and enqueue it
|
||||
visited[startVertex] = True
|
||||
queue.append(startVertex)
|
||||
|
||||
while queue:
|
||||
startVertex = queue.pop(0)
|
||||
print(startVertex, end = ' ')
|
||||
|
||||
# mark all adjacent nodes as visited and print them
|
||||
for i in self.vertex[startVertex]:
|
||||
if visited[i] == False:
|
||||
queue.append(i)
|
||||
visited[i] = True
|
||||
|
||||
if __name__ == '__main__':
|
||||
g = Graph()
|
||||
g.addEdge(0, 1)
|
||||
g.addEdge(0, 2)
|
||||
g.addEdge(1, 2)
|
||||
g.addEdge(2, 0)
|
||||
g.addEdge(2, 3)
|
||||
g.addEdge(3, 3)
|
||||
|
||||
g.printGraph()
|
||||
print('BFS:')
|
||||
g.BFS(2)
|
||||
|
||||
# OUTPUT:
|
||||
# 0 -> 1 -> 2
|
||||
# 1 -> 2
|
||||
# 2 -> 0 -> 3
|
||||
# 3 -> 3
|
||||
# BFS:
|
||||
# 2 0 3 1
|
66
data_structures/graph/depth_first_search.py
Normal file
66
data_structures/graph/depth_first_search.py
Normal file
@ -0,0 +1,66 @@
|
||||
#!/usr/bin/python
|
||||
# encoding=utf8
|
||||
|
||||
""" Author: OMKAR PATHAK """
|
||||
from __future__ import print_function
|
||||
|
||||
|
||||
class Graph():
|
||||
def __init__(self):
|
||||
self.vertex = {}
|
||||
|
||||
# for printing the Graph vertexes
|
||||
def printGraph(self):
|
||||
print(self.vertex)
|
||||
for i in self.vertex.keys():
|
||||
print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]]))
|
||||
|
||||
# for adding the edge beween two vertexes
|
||||
def addEdge(self, fromVertex, toVertex):
|
||||
# check if vertex is already present,
|
||||
if fromVertex in self.vertex.keys():
|
||||
self.vertex[fromVertex].append(toVertex)
|
||||
else:
|
||||
# else make a new vertex
|
||||
self.vertex[fromVertex] = [toVertex]
|
||||
|
||||
def DFS(self):
|
||||
# visited array for storing already visited nodes
|
||||
visited = [False] * len(self.vertex)
|
||||
|
||||
# call the recursive helper function
|
||||
for i in range(len(self.vertex)):
|
||||
if visited[i] == False:
|
||||
self.DFSRec(i, visited)
|
||||
|
||||
def DFSRec(self, startVertex, visited):
|
||||
# mark start vertex as visited
|
||||
visited[startVertex] = True
|
||||
|
||||
print(startVertex, end = ' ')
|
||||
|
||||
# Recur for all the vertexes that are adjacent to this node
|
||||
for i in self.vertex.keys():
|
||||
if visited[i] == False:
|
||||
self.DFSRec(i, visited)
|
||||
|
||||
if __name__ == '__main__':
|
||||
g = Graph()
|
||||
g.addEdge(0, 1)
|
||||
g.addEdge(0, 2)
|
||||
g.addEdge(1, 2)
|
||||
g.addEdge(2, 0)
|
||||
g.addEdge(2, 3)
|
||||
g.addEdge(3, 3)
|
||||
|
||||
g.printGraph()
|
||||
print('DFS:')
|
||||
g.DFS()
|
||||
|
||||
# OUTPUT:
|
||||
# 0 -> 1 -> 2
|
||||
# 1 -> 2
|
||||
# 2 -> 0 -> 3
|
||||
# 3 -> 3
|
||||
# DFS:
|
||||
# 0 1 2 3
|
57
data_structures/graph/dijkstra.py
Normal file
57
data_structures/graph/dijkstra.py
Normal file
@ -0,0 +1,57 @@
|
||||
from __future__ import print_function
|
||||
|
||||
def printDist(dist, V):
|
||||
print("\nVertex Distance")
|
||||
for i in range(V):
|
||||
if dist[i] != float('inf') :
|
||||
print(i,"\t",int(dist[i]),end = "\t")
|
||||
else:
|
||||
print(i,"\t","INF",end="\t")
|
||||
print()
|
||||
|
||||
def minDist(mdist, vset, V):
|
||||
minVal = float('inf')
|
||||
minInd = -1
|
||||
for i in range(V):
|
||||
if (not vset[i]) and mdist[i] < minVal :
|
||||
minInd = i
|
||||
minVal = mdist[i]
|
||||
return minInd
|
||||
|
||||
def Dijkstra(graph, V, src):
|
||||
mdist=[float('inf') for i in range(V)]
|
||||
vset = [False for i in range(V)]
|
||||
mdist[src] = 0.0;
|
||||
|
||||
for i in range(V-1):
|
||||
u = minDist(mdist, vset, V)
|
||||
vset[u] = True
|
||||
|
||||
for v in range(V):
|
||||
if (not vset[v]) and graph[u][v]!=float('inf') and mdist[u] + graph[u][v] < mdist[v]:
|
||||
mdist[v] = mdist[u] + graph[u][v]
|
||||
|
||||
|
||||
|
||||
printDist(mdist, V)
|
||||
|
||||
|
||||
|
||||
#MAIN
|
||||
V = int(raw_input("Enter number of vertices: "))
|
||||
E = int(raw_input("Enter number of edges: "))
|
||||
|
||||
graph = [[float('inf') for i in range(V)] for j in range(V)]
|
||||
|
||||
for i in range(V):
|
||||
graph[i][i] = 0.0
|
||||
|
||||
for i in range(E):
|
||||
print("\nEdge ",i+1)
|
||||
src = int(raw_input("Enter source:"))
|
||||
dst = int(raw_input("Enter destination:"))
|
||||
weight = float(raw_input("Enter weight:"))
|
||||
graph[src][dst] = weight
|
||||
|
||||
gsrc = int(raw_input("\nEnter shortest path source:"))
|
||||
Dijkstra(graph, V, gsrc)
|
212
data_structures/graph/dijkstra_algorithm.py
Normal file
212
data_structures/graph/dijkstra_algorithm.py
Normal file
@ -0,0 +1,212 @@
|
||||
# Title: Dijkstra's Algorithm for finding single source shortest path from scratch
|
||||
# Author: Shubham Malik
|
||||
# References: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
|
||||
|
||||
from __future__ import print_function
|
||||
import math
|
||||
import sys
|
||||
# For storing the vertex set to retreive node with the lowest distance
|
||||
|
||||
|
||||
class PriorityQueue:
|
||||
# Based on Min Heap
|
||||
def __init__(self):
|
||||
self.cur_size = 0
|
||||
self.array = []
|
||||
self.pos = {} # To store the pos of node in array
|
||||
|
||||
def isEmpty(self):
|
||||
return self.cur_size == 0
|
||||
|
||||
def min_heapify(self, idx):
|
||||
lc = self.left(idx)
|
||||
rc = self.right(idx)
|
||||
if lc < self.cur_size and self.array(lc)[0] < self.array(idx)[0]:
|
||||
smallest = lc
|
||||
else:
|
||||
smallest = idx
|
||||
if rc < self.cur_size and self.array(rc)[0] < self.array(smallest)[0]:
|
||||
smallest = rc
|
||||
if smallest != idx:
|
||||
self.swap(idx, smallest)
|
||||
self.min_heapify(smallest)
|
||||
|
||||
def insert(self, tup):
|
||||
# Inserts a node into the Priority Queue
|
||||
self.pos[tup[1]] = self.cur_size
|
||||
self.cur_size += 1
|
||||
self.array.append((sys.maxsize, tup[1]))
|
||||
self.decrease_key((sys.maxsize, tup[1]), tup[0])
|
||||
|
||||
def extract_min(self):
|
||||
# Removes and returns the min element at top of priority queue
|
||||
min_node = self.array[0][1]
|
||||
self.array[0] = self.array[self.cur_size - 1]
|
||||
self.cur_size -= 1
|
||||
self.min_heapify(1)
|
||||
del self.pos[min_node]
|
||||
return min_node
|
||||
|
||||
def left(self, i):
|
||||
# returns the index of left child
|
||||
return 2 * i + 1
|
||||
|
||||
def right(self, i):
|
||||
# returns the index of right child
|
||||
return 2 * i + 2
|
||||
|
||||
def par(self, i):
|
||||
# returns the index of parent
|
||||
return math.floor(i / 2)
|
||||
|
||||
def swap(self, i, j):
|
||||
# swaps array elements at indices i and j
|
||||
# update the pos{}
|
||||
self.pos[self.array[i][1]] = j
|
||||
self.pos[self.array[j][1]] = i
|
||||
temp = self.array[i]
|
||||
self.array[i] = self.array[j]
|
||||
self.array[j] = temp
|
||||
|
||||
def decrease_key(self, tup, new_d):
|
||||
idx = self.pos[tup[1]]
|
||||
# assuming the new_d is atmost old_d
|
||||
self.array[idx] = (new_d, tup[1])
|
||||
while idx > 0 and self.array[self.par(idx)][0] > self.array[idx][0]:
|
||||
self.swap(idx, self.par(idx))
|
||||
idx = self.par(idx)
|
||||
|
||||
|
||||
class Graph:
|
||||
def __init__(self, num):
|
||||
self.adjList = {} # To store graph: u -> (v,w)
|
||||
self.num_nodes = num # Number of nodes in graph
|
||||
# To store the distance from source vertex
|
||||
self.dist = [0] * self.num_nodes
|
||||
self.par = [-1] * self.num_nodes # To store the path
|
||||
|
||||
def add_edge(self, u, v, w):
|
||||
# Edge going from node u to v and v to u with weight w
|
||||
# u (w)-> v, v (w) -> u
|
||||
# Check if u already in graph
|
||||
if u in self.adjList.keys():
|
||||
self.adjList[u].append((v, w))
|
||||
else:
|
||||
self.adjList[u] = [(v, w)]
|
||||
|
||||
# Assuming undirected graph
|
||||
if v in self.adjList.keys():
|
||||
self.adjList[v].append((u, w))
|
||||
else:
|
||||
self.adjList[v] = [(u, w)]
|
||||
|
||||
def show_graph(self):
|
||||
# u -> v(w)
|
||||
for u in self.adjList:
|
||||
print(u, '->', ' -> '.join(str("{}({})".format(v, w))
|
||||
for v, w in self.adjList[u]))
|
||||
|
||||
def dijkstra(self, src):
|
||||
# Flush old junk values in par[]
|
||||
self.par = [-1] * self.num_nodes
|
||||
# src is the source node
|
||||
self.dist[src] = 0
|
||||
Q = PriorityQueue()
|
||||
Q.insert((0, src)) # (dist from src, node)
|
||||
for u in self.adjList.keys():
|
||||
if u != src:
|
||||
self.dist[u] = sys.maxsize # Infinity
|
||||
self.par[u] = -1
|
||||
|
||||
while not Q.isEmpty():
|
||||
u = Q.extract_min() # Returns node with the min dist from source
|
||||
# Update the distance of all the neighbours of u and
|
||||
# if their prev dist was INFINITY then push them in Q
|
||||
for v, w in self.adjList[u]:
|
||||
new_dist = self.dist[u] + w
|
||||
if self.dist[v] > new_dist:
|
||||
if self.dist[v] == sys.maxsize:
|
||||
Q.insert((new_dist, v))
|
||||
else:
|
||||
Q.decrease_key((self.dist[v], v), new_dist)
|
||||
self.dist[v] = new_dist
|
||||
self.par[v] = u
|
||||
|
||||
# Show the shortest distances from src
|
||||
self.show_distances(src)
|
||||
|
||||
def show_distances(self, src):
|
||||
print("Distance from node: {}".format(src))
|
||||
for u in range(self.num_nodes):
|
||||
print('Node {} has distance: {}'.format(u, self.dist[u]))
|
||||
|
||||
def show_path(self, src, dest):
|
||||
# To show the shortest path from src to dest
|
||||
# WARNING: Use it *after* calling dijkstra
|
||||
path = []
|
||||
cost = 0
|
||||
temp = dest
|
||||
# Backtracking from dest to src
|
||||
while self.par[temp] != -1:
|
||||
path.append(temp)
|
||||
if temp != src:
|
||||
for v, w in self.adjList[temp]:
|
||||
if v == self.par[temp]:
|
||||
cost += w
|
||||
break
|
||||
temp = self.par[temp]
|
||||
path.append(src)
|
||||
path.reverse()
|
||||
|
||||
print('----Path to reach {} from {}----'.format(dest, src))
|
||||
for u in path:
|
||||
print('{}'.format(u), end=' ')
|
||||
if u != dest:
|
||||
print('-> ', end='')
|
||||
|
||||
print('\nTotal cost of path: ', cost)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
graph = Graph(9)
|
||||
graph.add_edge(0, 1, 4)
|
||||
graph.add_edge(0, 7, 8)
|
||||
graph.add_edge(1, 2, 8)
|
||||
graph.add_edge(1, 7, 11)
|
||||
graph.add_edge(2, 3, 7)
|
||||
graph.add_edge(2, 8, 2)
|
||||
graph.add_edge(2, 5, 4)
|
||||
graph.add_edge(3, 4, 9)
|
||||
graph.add_edge(3, 5, 14)
|
||||
graph.add_edge(4, 5, 10)
|
||||
graph.add_edge(5, 6, 2)
|
||||
graph.add_edge(6, 7, 1)
|
||||
graph.add_edge(6, 8, 6)
|
||||
graph.add_edge(7, 8, 7)
|
||||
graph.show_graph()
|
||||
graph.dijkstra(0)
|
||||
graph.show_path(0, 4)
|
||||
|
||||
# OUTPUT
|
||||
# 0 -> 1(4) -> 7(8)
|
||||
# 1 -> 0(4) -> 2(8) -> 7(11)
|
||||
# 7 -> 0(8) -> 1(11) -> 6(1) -> 8(7)
|
||||
# 2 -> 1(8) -> 3(7) -> 8(2) -> 5(4)
|
||||
# 3 -> 2(7) -> 4(9) -> 5(14)
|
||||
# 8 -> 2(2) -> 6(6) -> 7(7)
|
||||
# 5 -> 2(4) -> 3(14) -> 4(10) -> 6(2)
|
||||
# 4 -> 3(9) -> 5(10)
|
||||
# 6 -> 5(2) -> 7(1) -> 8(6)
|
||||
# Distance from node: 0
|
||||
# Node 0 has distance: 0
|
||||
# Node 1 has distance: 4
|
||||
# Node 2 has distance: 12
|
||||
# Node 3 has distance: 19
|
||||
# Node 4 has distance: 21
|
||||
# Node 5 has distance: 11
|
||||
# Node 6 has distance: 9
|
||||
# Node 7 has distance: 8
|
||||
# Node 8 has distance: 14
|
||||
# ----Path to reach 4 from 0----
|
||||
# 0 -> 7 -> 6 -> 5 -> 4
|
||||
# Total cost of path: 21
|
70
data_structures/graph/even_tree.py
Normal file
70
data_structures/graph/even_tree.py
Normal file
@ -0,0 +1,70 @@
|
||||
"""
|
||||
You are given a tree(a simple connected graph with no cycles). The tree has N
|
||||
nodes numbered from 1 to N and is rooted at node 1.
|
||||
|
||||
Find the maximum number of edges you can remove from the tree to get a forest
|
||||
such that each connected component of the forest contains an even number of
|
||||
nodes.
|
||||
|
||||
Constraints
|
||||
2 <= 2 <= 100
|
||||
|
||||
Note: The tree input will be such that it can always be decomposed into
|
||||
components containing an even number of nodes.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
# pylint: disable=invalid-name
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
def dfs(start):
|
||||
"""DFS traversal"""
|
||||
# pylint: disable=redefined-outer-name
|
||||
ret = 1
|
||||
visited[start] = True
|
||||
for v in tree.get(start):
|
||||
if v not in visited:
|
||||
ret += dfs(v)
|
||||
if ret % 2 == 0:
|
||||
cuts.append(start)
|
||||
return ret
|
||||
|
||||
|
||||
def even_tree():
|
||||
"""
|
||||
2 1
|
||||
3 1
|
||||
4 3
|
||||
5 2
|
||||
6 1
|
||||
7 2
|
||||
8 6
|
||||
9 8
|
||||
10 8
|
||||
On removing edges (1,3) and (1,6), we can get the desired result 2.
|
||||
"""
|
||||
dfs(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
n, m = 10, 9
|
||||
tree = defaultdict(list)
|
||||
visited = {}
|
||||
cuts = []
|
||||
count = 0
|
||||
edges = [
|
||||
(2, 1),
|
||||
(3, 1),
|
||||
(4, 3),
|
||||
(5, 2),
|
||||
(6, 1),
|
||||
(7, 2),
|
||||
(8, 6),
|
||||
(9, 8),
|
||||
(10, 8),
|
||||
]
|
||||
for u, v in edges:
|
||||
tree[u].append(v)
|
||||
tree[v].append(u)
|
||||
even_tree()
|
||||
print(len(cuts) - 1)
|
48
data_structures/graph/floyd_warshall.py
Normal file
48
data_structures/graph/floyd_warshall.py
Normal file
@ -0,0 +1,48 @@
|
||||
from __future__ import print_function
|
||||
|
||||
def printDist(dist, V):
|
||||
print("\nThe shortest path matrix using Floyd Warshall algorithm\n")
|
||||
for i in range(V):
|
||||
for j in range(V):
|
||||
if dist[i][j] != float('inf') :
|
||||
print(int(dist[i][j]),end = "\t")
|
||||
else:
|
||||
print("INF",end="\t")
|
||||
print()
|
||||
|
||||
|
||||
|
||||
def FloydWarshall(graph, V):
|
||||
dist=[[float('inf') for i in range(V)] for j in range(V)]
|
||||
|
||||
for i in range(V):
|
||||
for j in range(V):
|
||||
dist[i][j] = graph[i][j]
|
||||
|
||||
for k in range(V):
|
||||
for i in range(V):
|
||||
for j in range(V):
|
||||
if dist[i][k]!=float('inf') and dist[k][j]!=float('inf') and dist[i][k]+dist[k][j] < dist[i][j]:
|
||||
dist[i][j] = dist[i][k] + dist[k][j]
|
||||
|
||||
printDist(dist, V)
|
||||
|
||||
|
||||
|
||||
#MAIN
|
||||
V = int(raw_input("Enter number of vertices: "))
|
||||
E = int(raw_input("Enter number of edges: "))
|
||||
|
||||
graph = [[float('inf') for i in range(V)] for j in range(V)]
|
||||
|
||||
for i in range(V):
|
||||
graph[i][i] = 0.0
|
||||
|
||||
for i in range(E):
|
||||
print("\nEdge ",i+1)
|
||||
src = int(raw_input("Enter source:"))
|
||||
dst = int(raw_input("Enter destination:"))
|
||||
weight = float(raw_input("Enter weight:"))
|
||||
graph[src][dst] = weight
|
||||
|
||||
FloydWarshall(graph, V)
|
44
data_structures/graph/graph.py
Normal file
44
data_structures/graph/graph.py
Normal file
@ -0,0 +1,44 @@
|
||||
#!/usr/bin/python
|
||||
# encoding=utf8
|
||||
|
||||
from __future__ import print_function
|
||||
# Author: OMKAR PATHAK
|
||||
|
||||
# We can use Python's dictionary for constructing the graph
|
||||
|
||||
class AdjacencyList(object):
|
||||
def __init__(self):
|
||||
self.List = {}
|
||||
|
||||
def addEdge(self, fromVertex, toVertex):
|
||||
# check if vertex is already present
|
||||
if fromVertex in self.List.keys():
|
||||
self.List[fromVertex].append(toVertex)
|
||||
else:
|
||||
self.List[fromVertex] = [toVertex]
|
||||
|
||||
def printList(self):
|
||||
for i in self.List:
|
||||
print((i,'->',' -> '.join([str(j) for j in self.List[i]])))
|
||||
|
||||
if __name__ == '__main__':
|
||||
al = AdjacencyList()
|
||||
al.addEdge(0, 1)
|
||||
al.addEdge(0, 4)
|
||||
al.addEdge(4, 1)
|
||||
al.addEdge(4, 3)
|
||||
al.addEdge(1, 0)
|
||||
al.addEdge(1, 4)
|
||||
al.addEdge(1, 3)
|
||||
al.addEdge(1, 2)
|
||||
al.addEdge(2, 3)
|
||||
al.addEdge(3, 4)
|
||||
|
||||
al.printList()
|
||||
|
||||
# OUTPUT:
|
||||
# 0 -> 1 -> 4
|
||||
# 1 -> 0 -> 4 -> 3 -> 2
|
||||
# 2 -> 3
|
||||
# 3 -> 4
|
||||
# 4 -> 1 -> 3
|
31
data_structures/graph/graph_list.py
Normal file
31
data_structures/graph/graph_list.py
Normal file
@ -0,0 +1,31 @@
|
||||
from __future__ import print_function
|
||||
|
||||
|
||||
class Graph:
|
||||
def __init__(self, vertex):
|
||||
self.vertex = vertex
|
||||
self.graph = [[0] for i in range(vertex)]
|
||||
|
||||
def add_edge(self, u, v):
|
||||
self.graph[u - 1].append(v - 1)
|
||||
|
||||
def show(self):
|
||||
for i in range(self.vertex):
|
||||
print('%d: '% (i + 1), end=' ')
|
||||
for j in self.graph[i]:
|
||||
print('%d-> '% (j + 1), end=' ')
|
||||
print(' ')
|
||||
|
||||
|
||||
|
||||
g = Graph(100)
|
||||
|
||||
g.add_edge(1,3)
|
||||
g.add_edge(2,3)
|
||||
g.add_edge(3,4)
|
||||
g.add_edge(3,5)
|
||||
g.add_edge(4,5)
|
||||
|
||||
|
||||
g.show()
|
||||
|
32
data_structures/graph/graph_matrix.py
Normal file
32
data_structures/graph/graph_matrix.py
Normal file
@ -0,0 +1,32 @@
|
||||
from __future__ import print_function
|
||||
|
||||
|
||||
class Graph:
|
||||
|
||||
def __init__(self, vertex):
|
||||
self.vertex = vertex
|
||||
self.graph = [[0] * vertex for i in range(vertex) ]
|
||||
|
||||
def add_edge(self, u, v):
|
||||
self.graph[u - 1][v - 1] = 1
|
||||
self.graph[v - 1][u - 1] = 1
|
||||
|
||||
def show(self):
|
||||
|
||||
for i in self.graph:
|
||||
for j in i:
|
||||
print(j, end=' ')
|
||||
print(' ')
|
||||
|
||||
|
||||
|
||||
|
||||
g = Graph(100)
|
||||
|
||||
g.add_edge(1,4)
|
||||
g.add_edge(4,2)
|
||||
g.add_edge(4,5)
|
||||
g.add_edge(2,5)
|
||||
g.add_edge(5,3)
|
||||
g.show()
|
||||
|
Reference in New Issue
Block a user