Saturday, November 14, 2015

BFS

Use bfs function included here.
https://github.com/prabushitha/DataStructures/blob/master/Graph/GraphBFS.py

Output:
bfs(graph,source) returns an array with shortest distances for each vertex in the graph
array element is None when there's no path

Usage:
If you want to print distances from 3 to other vertexes, call bfs function with the source vertex 3. print(bfs(graph,3))

Tuesday, November 10, 2015

Creating a graph according the user input

Firstly,
මේ පයිතන් graph class 2ක දාගන්න (class Node and class Graph)
https://raw.githubusercontent.com/prabushitha/DataStructures/master/Graph/GraphAL.py

Okay!
දැන් User input දෙන්නේ මේ විදියට කියලා හිතමු

1 2
1 3
2 4
4 5
END
ඉහත ආකාරය දක්වා ඇත්තේ
Edge එක පටන් ගන්න Vertex එක <SPACE> Edge එක ඉවර වෙන Vertex එක
eg. 1 2 කියලා කියන්නේ
පලවෙනි Vertex එකේ ඉදන් දෙවනි Vertex එකට Edge එකක් තියන්වයි කියල.

END කියලා input එක දුන්නම එතනින් ඉවරයි කියලා ගන්නවා

So, the graph should look like this

















ඕක graph එකට දාගන්න කෝඩ් එක දැන් අපි ලියමු.

graph = Graph()
while(True):
   userInput = str(input())
   if(userInput=="END"):
      break
   vertexFrom = userInput.split()[0]
   vertexTo = userInput.split()[1]
   #Creating the vertexes if vertexes are not already created
   if(not graph.isVertex(vertexFrom)):
      graph.addVertex(vertexFrom)
   if(not graph.isVertex(vertexTo)):
      graph.addVertex(vertexTo)
   graph.addEdge(vertexFrom,vertexTo)
print(graph)

ඔච්චර තමා කරන්න තියෙන්නේ. ඊට පස්සේ තියෙන්නේ හදාගත්ත graph එකෙන් වැඩ ගන්න එක :-D
ඒ කියන්නේ BFS දාල Shortest path හොයන සීන් වගේ එව්වා :-D

<download fullcode here: https://raw.githubusercontent.com/prabushitha/DataStructures/master/Graph/Example/GraphExample.py 
>

Monday, November 9, 2015

Graph implementation using linkedlists

Here's my python class
(Includes class Node and class Graph)
https://raw.githubusercontent.com/prabushitha/DataStructures/master/Graph/GraphAL.py

Usage
#After copying/importing above 2 classes to your code

#Creating a new graph

graph = Graph()

#Adding a vertex. e.g add 2 vertexes A and B
graph.addVertex("A")
graph.addVertex("B")

#Adding an edge between 2 vertexes 
graph.addEdge("A","B")

#Check whether there's an edge between 2 vertexes. e.g from A to B (returns True/False)
graph.isEdge("A","C")
#Check whether there's a path from one vertex to another. e.g from A to B (returns True/False)
graph.isPath("D","B")