About
def
------------------------------------------------------------------------binary tree----------------------------------------------------
class BinaryTree: class node: def _init_(self): self.element = 0 self.parent = None self.leftchild = None self.rightchild = None
def _init_(self):
self.sz = 0
self.root = self.node()
self.ht = 0
def getChildren(self, curnode):
children = []
if curnode.leftchild != None:
children.append(curnode.leftchild)
if curnode.rightchild != None:
children.append(curnode.rightchild)
return children
def isExternal(self, curnode):
if (curnode.leftchild == None and curnode.rightchild == None):
return (True)
else:
return (False)
def isRoot(self, curnode):
if (curnode.parent == None):
return True
else:
return False
def inorderTraverse(self, v):
# @start-editable@
if not v:
return
else:
self.inorderTraverse(v.leftchild)
print(v.element, end=",")
self.inorderTraverse(v.rightchild)
# @end-editable@
def preorderTraverse(self, v):
# @start-editable@
if not v:
return
else:
print(v.element, end=",")
self.preorderTraverse(v.leftchild)
self.preorderTraverse(v.rightchild)
# @end-editable@
def postorderTraverse(self, v):
# @start-editable@
if not v:
return
else:
self.postorderTraverse(v.leftchild)
self.postorderTraverse(v.rightchild)
print(v.element, end=",")
# @end-editable@
def levelorderTraverse(self, v):
# @start-editable@
q = []
q.append(v)
while len(q) is not 0:
p = q[0]
print(q[0].element, end=",")
q.pop(0)
if (p.leftchild is not None):
q.append(p.leftchild)
if (p.rightchild is not None):
q.append(p.rightchild)
# @end-editable@
def findDepth(self, v):
# @start-editable@
if self.isRoot(v):
return 0
else:
return 1 + self.findDepth(v.parent)
# @end-editable@
def findHeight(self, v):
# @start-editable@
if self.isExternal(v):
return 0
else:
h = 0
for w in self.getChildren(v):
h = max(h, self.findHeight(w))
return h + 1
# @end-editable@
# delete leaves in the tree
def delLeaves(self, v):
# @start-editable@
if v == None:
return None
if v.leftchild == None and v.rightchild == None:
return None
v.leftchild = self.delLeaves(v.leftchild)
v.rightchild = self.delLeaves(v.rightchild)
return v
# @end-editable@
# returns true if tree is proper
def isProper(self, v):
# @start-editable@
if v is None:
return True
if v.leftchild is None and v.rightchild is None:
return True
if v.leftchild is not None and v.rightchild is not None:
return (self.isProper(v.leftchild) and self.isProper(v.rightchild))
return False
# @end-editable@
# create a tree that is a mirror image of the original tree and print its levelorder
def mirror(self, v):
# @start-editable@
if v is None:
return
else:
temp = v
self.mirror(v.leftchild)
self.mirror(v.rightchild)
temp = v.leftchild
v.leftchild = v.rightchild
v.rightchild = temp
# @end-editable@
def buildTree(self, eltlist):
nodelist = []
nodelist.append(None)
for i in range(len(eltlist)):
if (i != 0):
if (eltlist[i] != -1):
tempnode = self.node()
tempnode.element = eltlist[i]
if i != 1:
tempnode.parent = nodelist[int(i / 2)]
if (i % 2 == 0):
nodelist[int(i / 2)].leftchild = tempnode
else:
nodelist[int(i / 2)].rightchild = tempnode
nodelist.append(tempnode)
else:
nodelist.append(None)
self.root = nodelist[1]
self.sz = len(nodelist)
return nodelist
# write a function to visualize the tree
def printTree(self, nlist):
for i in range(len(nlist)):
if (nlist[i] != None):
print(nlist[i].element, end=" ");
else:
print(None)
def isEmpty(self):
return (self.sz == 0)
def size(self):
return self.sz
# determine whether there exists a root-to-leaf path whose nodes sum is equal to a specified integer
def root2leafsum(self, k):
# @start-editable@
def innerloop(node, k):
if node is None:
return k == 0
ans = 0
subsum = k - node.element
if (subsum == 0 and node.leftchild == None and node.rightchild == None):
return True
if (node.leftchild is not None):
ans = ans or innerloop(node.leftchild, subsum)
if node.rightchild is not None:
ans = ans or innerloop(node.rightchild, subsum)
return ans
p = innerloop(self.root, k)
if (p):
print("True")
else:
print("False")
# @end-editable@
# determine the value of the leaf node in a given binary tree that is the terminal node of a path of least value from the root of the binary tree to any leaf. The value of a path is the sum of values of nodes along that path.
def leastleaf(self):
# @start-editable@
def innerloop(node, subsum):
minsum = 1000000
minleaf = 0
subsum += node.element
if (node.leftchild == None and node.rightchild == None):
return subsum, node.element
if node.leftchild is not None:
left, leftele = innerloop(node.leftchild, subsum)
if (left < minsum):
minsum = left
minleaf = leftele
if (left == minsum):
minleaf = min(minleaf, leftele)
if node.rightchild is not None:
right, rightele = innerloop(node.rightchild, subsum)
if (right < minsum):
minsum = right
minleaf = rightele
if (right == minsum):
minleaf = min(minleaf, rightele)
return minsum, minleaf
p, q = innerloop(self.root, 0)
print(q)
# @end-editable@
def main(): tree = BinaryTree() arraySize = int(input()) arr = list(map(int, input().split())) nlist = tree.buildTree(arr) inputs = int(input()) while inputs > 0: command = input() operation = command.split() if (operation[0] == "I"): tree.inorderTraverse(tree.root) print() elif (operation[0] == "P"): tree.preorderTraverse(tree.root) print() elif (operation[0] == "Post"): tree.postorderTraverse(tree.root) print() elif (operation[0] == "L"): tree.levelorderTraverse(tree.root) print() elif (operation[0] == "D"): pos = int(operation[1]) print(tree.findDepth(nlist[pos])) elif (operation[0] == "H"): pos = int(operation[1]) print(tree.findHeight(nlist[pos])) elif (operation[0] == "IP"): print(tree.isProper(tree.root)) elif (operation[0] == 'M'): tree.mirror(tree.root) tree.levelorderTraverse(tree.root) print() elif (operation[0] == 'DL'): tree.delLeaves(tree.root) tree.levelorderTraverse(tree.root) print() elif (operation[0] == 'RL'): tree.root2leafsum(int(operation[1])) print() elif (operation[0] == 'ML'): tree.leastleaf() print() inputs -= 1
if _name_ == '_main_': main()
-----------------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------graph--------------------------------------------------------------------------
from collections import OrderedDict class BinHeap(): def __init__(self): self.heapList = [0] self.currentSize = 0 def upHeapp(self, i): while i // 2 > 0: if self.heapList[i] < self.heapList[i // 2]: self.heapList[i], self.heapList[i // 2] = self.heapList[i // 2], self.heapList[i] i = i // 2
def insert(self, k):
self.heapList.append(k)
self.currentSize += 1
self.upHeapp(self.currentSize)
def size(self):
return self.currentSize
def downHeap(self, i):
while (i * 2) <= self.currentSize:
min = self.minChild(i)
if self.heapList[i] > self.heapList[min]:
self.heapList[i], self.heapList[min] = self.heapList[min], self.heapList[i]
i = min
def minChild(self, i):
if (i * 2) + 1 > self.currentSize:
return i * 2
else:
if self.heapList[i * 2] < self.heapList[(i * 2) + 1]:
return i * 2
else:
return (i * 2) + 1
def delMin(self):
if len(self.heapList) == 1:
return 'Empty heap'
root = self.heapList[1]
self.heapList[1] = self.heapList[self.currentSize]
self.heapList.pop(self.currentSize)
self.currentSize -= 1
self.downHeap(1)
# self.printHeap()
return root
def printHeap(self):
print(self.heapList)
class Vertex: def __init__(self, key): self.id = key self.connectedTo = {}
def addNeighbor(self, nbr, weight=0):
self.connectedTo[nbr] = weight
def __str__(self):
return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo])
def getConnections(self):
return self.connectedTo.keys()
def getId(self):
return self.id
def getWeight(self, nbr):
return self.connectedTo[nbr]
class Graph: def __init__(self): self.vertList = {} self.numVertices = 0 self.front = [] self.back = [] self.depfs = []
def addVertex(self, key):
self.numVertices = self.numVertices + 1
newVertex = Vertex(key)
self.vertList[key] = newVertex
self.vertList = OrderedDict(sorted(self.vertList.items()))
return newVertex
def getVertex(self, n):
if n in self.vertList:
return self.vertList[n]
else:
return None
def __contains__(self, n):
return n in self.vertList
def addEdge(self, f, t, cost=0): # f is from node, t is to node
if f not in self.vertList:
nv = self.addVertex(f)
if t not in self.vertList:
nv = self.addVertex(t)
self.vertList[f].addNeighbor(self.vertList[t], cost)
def addVertex(self, key):
self.numVertices = self.numVertices + 1
newVertex = Vertex(key)
self.vertList[key] = newVertex
self.vertList = OrderedDict(sorted(self.vertList.items()))
return newVertex
def getVertices(self):
return self.vertList.keys()
def __iter__(self):
return iter(self.vertList.values())
def createAdjMatrix(self):
adjmat = list()
# @start-editable@
for t in range(self.numVertices + 1):
for k in range(self.numVertices + 1):
adjmat.insert(t, [0 for k in range(self.numVertices + 1)])
for p in self:
for o in p.getConnections():
adjmat[p.getId()][o.getId()] = p.getWeight(o)
# @end-editable@
print("Adjacency matrix")
for i in range(self.numVertices):
for j in range(self.numVertices):
print(adjmat[i][j], end=" ")
print("")
return
def printdfs(self):
print("Front edges:", self.front)
print("Back edges:", self.back)
print("dfs:", self.depfs)
def dfs(self, stnode):
self.depfs.append(stnode.getId())
neighbours = list(stnode.getConnections())
# @start-editable@
for i in neighbours:
if i.getId() not in self.depfs:
self.front.append([stnode.getId(), i.getId()])
self.dfs(i)
else:
self.back.append([stnode.getId(), i.getId()])
if i.getId() not in self.depfs:
self.depfs.append(i.getId())
return self.depfs
# @end-editable@
return
def bfs(self, stnode):
queue = []
breadth = []
cross = []
breadth.append(stnode.getId())
queue.append(stnode.getId())
# @start-editable@
while len(queue) > 0:
current = queue.pop(0)
neighbours = list(self.vertList[current].getConnections())
for i in neighbours:
if i.getId() not in breadth:
breadth.append(i.getId())
queue.append(i.getId())
cross.append([current, i.getId()])
# @end-editable@
print("Bfs:", breadth)
print("Cross edge:", cross)
return
def mstKruskal(self):
wt = BinHeap()
edge = {}
tree = []
re = []
# @start-editable@
for i in self:
for j in self.getVertex(i.id).getConnections():
wt.insert(i.getWeight(j))
edge.update({i.getWeight(j): [i.id, j.id]})
def search(i):
if parent[i] == i:
return i
return search(parent[i])
def order(x, y):
xroot = search(x)
yroot = search(y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
parent = [i.id for i in self]
rank = [0 for i in self]
i, e = 0, 0
while e < self.numVertices and wt.heapList[1:]:
w = wt.delMin()
u = edge[w][0]
v = edge[w][1]
i = i + 1
x = search(u)
y = search(v)
if x != y:
e = e + 1
re.append([u, v])
order(x, y)
# @end-editable@
print("Minimum spanning tree:", sorted(re))
return
def testGraph(): g = Graph() for i in range(6): g.addVertex(i) g.vertList g.addEdge(5, 1, 8) g.addEdge(1, 2, 19) g.addEdge(5, 0, 10) g.addEdge(4, 6, 11) g.addEdge(6, 10, 23) g.addEdge(10, 9, 33) g.addEdge(9, 8, 7) g.addEdge(6, 7, 6) g.addEdge(8, 7, 1) g.addEdge(9, 6, 9) g.addEdge(7, 10, 14) g.addEdge(0, 4, 15) g.addEdge(0, 3, 16) g.addEdge(0, 2, 5) g.addEdge(0, 1, 2) g.addEdge(2, 3, 4) g.addEdge(3, 4, 30) g.addEdge(4, 5, 18) g.addEdge(5, 2, 22) g.addEdge(3, 1, 17)
for v in g:
for w in v.getConnections():
print("( %s , %s )" % (v.getId(), w.getId()))
inputs = int(input())
while inputs > 0:
command = input()
operation = command.split()
if (operation[0] == "A"):
AdjMat = g.createAdjMatrix()
elif (operation[0] == "B"):
start = g.getVertex(int(operation[1]))
g.bfs(start)
elif (operation[0] == "D"):
start = g.getVertex(int(operation[1]))
g.dfs(start)
g.printdfs()
elif (operation[0] == "M"):
g.mstKruskal()
inputs -= 1
def main(): testGraph()
if __name__ == '__main__': main()
-----------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------upheap-------------------------------------------------------------
@start-editable@
class RailwayReservation(): def __init__(self): self.Phonenumbers = [] self.nt = [] self.currentSize = 0
def upheap(self, i):
while i // 2 > 0:
if self.nt[i] > self.nt[(i // 2) - 1]:
self.nt[i], self.nt[(i // 2) - 1] = self.nt[(i // 2) - 1], self.nt[i]
self.Phonenumbers[i], self.Phonenumbers[(i // 2) - 1] = self.Phonenumbers[(i // 2) - 1], \
self.Phonenumbers[i]
i = i // 2 - 1
def sort(self, p, nt):
for i in range(len(nt)):
for j in range(i + 1, len(nt)):
if nt[j] > nt[i]:
t = p[j]
p[j] = p[i]
p[i] = t
t2 = nt[j]
nt[j] = nt[i]
nt[i] = t2
return p, nt
def reservationrequest(self, p, nt):
self.Phonenumbers.append(p)
self.nt.append(nt)
self.upheap(self.currentSize)
self.currentSize += 1
return
def printFinalReservationList(self):
t = self.Phonenumbers
t2 = self.nt
t, t2 = self.sort(t, t2)
print(t)
print(t2)
return
# create a method to print the current list reservation list
def printReservationList(self):
print(self.Phonenumbers)
print(self.nt)
def main(): R = RailwayReservation() arraySize = int(input()) inputs = int(input()) while inputs > 0: command = input() operation = command.split() if (operation[0] == "RR"): R.reservationrequest(int(operation[1]), int(operation[2])) R.printReservationList() elif (operation[0] == "F"): R.printFinalReservationList()
inputs -= 1
if __name__ == '__main__': main()
@end-editable@
------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------max heap----------------------------------------------------------------------------------
def max_heapify(A,k): l = left(k) r = right(k) if l < len(A) and A[l] > A[k]: largest = l else: largest = k if r < len(A) and A[r] > A[largest]: largest = r if largest != k: A[k], A[largest] = A[largest], A[k] max_heapify(A, largest)
def left(k): return 2 * k + 1
def right(i): return 2 * k + 2
def build_max_heap(A): n = int((len(A)//2)-1) for k in range(n, -1, -1): max_heapify(A,k)
A = [3,9,2,1,4,5] build_max_heap(A) print(A)
----------------------------------------min heap----------------------------------------------------------------------------------
def min_heapify(A,k): l = left(k) r = right(k) if l < len(A) and A[l] < A[k]: smallest = l else: smallest = k if r < len(A) and A[r] < A[smallest]: smallest = r if smallest != k: A[k], A[smallest] = A[smallest], A[k] min_heapify(A, smallest)
def left(k): return 2 * k + 1
def right(k): return 2 * k + 2
def build_min_heap(A): n = int((len(A)//2)-1) for k in range(n, -1, -1): min_heapify(A,k)
A = [3,9,2,1,4,5] build_min_heap(A) print(A)
----------------------------------max heap------------------------------------------------------------------------------
------------------------------------pre order using array(modify to post and in)--------------------------------------------------------------
void preorder(int index) { if(index>0 && tree[index]!='\0') { printf(" %c\n",tree[index]); preorder(get_left_child(index)); preorder(get_right_child(index)); } } int get_right_child(int index) {
if(tree[index]!='\0' && ((2*index)+1)<=complete_node)
return (2*index)+1;
return -1;
}
int get_left_child(int index) { if(tree[index]!='\0' && (2index)<=complete_node) return 2index; return -1; }
--------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------heap--------------------------------------------------------
class heaps: heapslist=[] def _init_(self,maxsize): self.heapslist.append(-1) self.maxsize=maxsize self.cursize=0 self.front=1
def insheap(self,val):
if(val<0):
print("Negative insertions not allowed!")
return
self.heapslist.append(val)
self.cursize=len(self.heapslist)
#heapify
par=(self.cursize-1)//2
ind=self.cursize-1
while(self.heapslist[par]>self.heapslist[ind]):
temp=self.heapslist[par]
self.heapslist[par]=self.heapslist[ind]
self.heapslist[ind]=temp
#self.heapslist[par],self.heapslist[ind]==self.heapslist[ind],self.heapslist[par]
ind=par
par=ind//2
def retmin(self):
return self.heapslist[1]
def printheap(self):
if(len(self.heapslist)>1):
for i in range(len(self.heapslist)-1):
if i==0:
continue
print(self.heapslist[i],end=",")
print(self.heapslist[i+1])
else:
print("heap empty!")
def delmin(self):
print("Minimum element about to be removed: ",self.retmin())
self.heapslist[1]=self.heapslist[self.cursize-1]
self.heapslist.pop(self.cursize-1)
self.cursize=len(self.heapslist)-1
self.front=1
#downheap
ind=self.front
while(2*ind+1<len(self.heapslist)):
if(self.heapslist[ind]>self.heapslist[2*ind] or self.heapslist[ind]>self.heapslist[2*ind+1]):
if(self.heapslist[2*ind]<self.heapslist[2*ind+1]):
temp=self.heapslist[ind]
self.heapslist[ind]=self.heapslist[2*ind]
self.heapslist[2*ind]=temp
ind=2*ind
else:
temp=self.heapslist[ind]
self.heapslist[ind]=self.heapslist[2*ind+1]
self.heapslist[2*ind+1]=temp
ind=2*ind+1
if _name_ == "_main_":
h=heaps(10)
h.insheap(8)
h.insheap(9)
h.insheap(1)
h.printheap()
h.delmin()
h.delmin()
h.delmin()
h.printheap()
-----------------------------------------------------------------------------------------------------
-------------------------------------------------binary tree c++------------------------------------
include <iostream>
include <stack>
using namespace std;
class Node
{
public:
int iData;
double dData;
Node pLeftChild;
Node pRightChild;
Node() : iData(0), dData(0.0), pLeftChild(NULL),
pRightChild(NULL)
{
}
~Node()
{
cout << "X-" << iData << " ";
}
void displayNode()
{
cout << '{' << iData << ", " << dData << "} ";
}
};
class BinaryTree
{
private:
Node* pRoot;
public:
BinaryTree() : pRoot(NULL)
{
}
Node find(int key)
{
Node pCurrent = pRoot;
while(pCurrent->iData != key)
{
if(key < pCurrent->iData)
pCurrent = pCurrent->pLeftChild;
else
pCurrent = pCurrent->pRightChild;
if(pCurrent == NULL)
return NULL;
}
return pCurrent;
}
void insert(int id, double dd)
{
Node pNewNode = new Node;
pNewNode->iData = id;
pNewNode->dData = dd;
pNewNode->pLeftChild = NULL;
pNewNode->pRightChild = NULL;
if(pRoot==NULL)
pRoot = pNewNode;
else
{
Node pCurrent = pRoot;
Node pParent;
while(true)
{
pParent = pCurrent;
if(id < pCurrent->iData)
{
pCurrent = pCurrent->pLeftChild;
if(pCurrent == NULL)
{
pParent->pLeftChild = pNewNode;
return;
}
}
else
{
pCurrent = pCurrent->pRightChild;
if(pCurrent == NULL)
{
pParent->pRightChild = pNewNode;
return;
}
}
}
}
}
void traverse(int traverseType)
{
switch(traverseType)
{
case 1: cout << "\nPreorder traversal: ";
preOrder(pRoot);
break;
case 2: cout << "\nInorder traversal: ";
inOrder(pRoot);
break;
case 3: cout << "\nPostorder traversal: ";
postOrder(pRoot);
break;
}
cout << endl;
}
void preOrder(Node pLocalRoot)
{
if(pLocalRoot != NULL)
{
cout << pLocalRoot->iData << " ";
preOrder(pLocalRoot->pLeftChild);
preOrder(pLocalRoot->pRightChild);
}
}
void inOrder(Node pLocalRoot)
{
if(pLocalRoot != NULL)
{
inOrder(pLocalRoot->pLeftChild);
cout << pLocalRoot->iData << " ";
inOrder(pLocalRoot->pRightChild);
}
}
void postOrder(Node pLocalRoot)
{
if(pLocalRoot != NULL)
{
postOrder(pLocalRoot->pLeftChild);
postOrder(pLocalRoot->pRightChild);
cout << pLocalRoot->iData << " ";
}
}
void displayTree()
{
stack<Node*> globalStack;
globalStack.push(pRoot);
int nBlanks = 32;
bool isRowEmpty = false;
cout << "......................................................";
cout << endl;
while(isRowEmpty==false)
{
stack<Node*> localStack;
isRowEmpty = true;
for(int j=0; j<nBlanks; j++)
cout << ' ';
while(globalStack.empty()==false)
{
Node* temp = globalStack.top();
globalStack.pop();
if(temp != NULL)
{
cout << temp->iData;
localStack.push(temp->pLeftChild);
localStack.push(temp->pRightChild);
if(temp->pLeftChild != NULL ||
temp->pRightChild != NULL)
isRowEmpty = false;
}
else
{
cout << "--";
localStack.push(NULL);
localStack.push(NULL);
}
for(int j=0; j<nBlanks*2-2; j++)
cout << ' ';
}
cout << endl;
nBlanks /= 2;
while(localStack.empty()==false)
{
globalStack.push( localStack.top() );
localStack.pop();
}
}
cout << "......................................................";
cout << endl;
} //end displayTree()
void destroy()
{
destroyRec(pRoot);
}
void destroyRec(Node* pLocalRoot)
{
if(pLocalRoot != NULL)
{
destroyRec(pLocalRoot->pLeftChild);
destroyRec(pLocalRoot->pRightChild);
delete pLocalRoot;
}
}
};
int main()
{
int value;
char choice;
Node* found;
BinaryTree theTree;
theTree.insert(50, 5.0);
theTree.insert(25, 2.5);
theTree.insert(75, 7.5);
theTree.insert(12, 1.2);
theTree.insert(37, 3.7);
theTree.insert(43, 4.3);
theTree.insert(30, 3.0);
theTree.insert(33, 3.3);
theTree.insert(87, 8.7);
theTree.insert(93, 9.3);
theTree.insert(97, 9.7);
while(choice != 'q')
{
cout << "Enter first letter of ";
cout << "show, insert, find, traverse or quit: ";
cin >> choice;
switch(choice)
{
case 's':
theTree.displayTree();
break;
case 'i':
cout << "Enter value to insert: ";
cin >> value;
theTree.insert(value, value + 0.9);
break;
case 'f':
cout << "Enter value to find: ";
cin >> value;
found = theTree.find(value);
if(found != NULL)
{
cout << "Found: ";
found->displayNode();
cout << endl;
}
else
cout << "Could not find " << value << endl;
break;
case 't':
cout << "Enter traverse type "
<< "(1=preorder, 2=inorder, 3=postorder): ";
cin >> value;
theTree.traverse(value);
break;
case 'q':
theTree.destroy();
cout << endl;
break;
default:
cout << "Invalid entry\n";
}
}
return 0;
}
--------------------------------------------------graphs c++(has bug)--------------------------------
include <iostream>
using namespace std;
class Graph { private: bool** adjMatrix; int numVertices;
public: // Initialize the matrix to zero Graph(int numVertices) { this->numVertices = numVertices; adjMatrix = new bool*[numVertices]; for (int i = 0; i < numVertices; i++) { adjMatrix[i] = new bool[numVertices]; for (int j = 0; j < numVertices; j++) adjMatrix[i][j] = false; } }
// Add edges void addEdge(int i, int j) { adjMatrix[i][j] = true; adjMatrix[j][i] = true; }
// Remove edges void removeEdge(int i, int j) { adjMatrix[i][j] = false; adjMatrix[j][i] = false; }
// Print the martix void toString() { for (int i = 0; i < numVertices; i++) { cout << i << " : "; for (int j = 0; j < numVertices; j++) cout << adjMatrix[i][j] << " "; cout << "\n"; } }
~Graph() { for (int i = 0; i < numVertices; i++) delete[] adjMatrix[i]; delete[] adjMatrix; } void dfs(int start, vector<bool>& visited) { cout << start << " "; for (int i = 0; i < adj[start].size(); i++) { if (adj[start][i] == 1 && (!visited[i])) { dfs(i, visited); } } } }; void bfs(int start) { vector<bool> visited(adj.size(), false); vector<int> q; q.push_back(start); visited[start] = true;
int vis;
while (!q.empty()) {
vis = q[0];
cout << vis << " ";
q.erase(q.begin());
for (int i = 0; i < adj[vis].size(); i++) {
if (adj[vis][i] == 1 && (!visited[i])) {
q.push_back(i);
// Set
visited[i] = true;
}
}
}
}
int main() { Graph g(4);
g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3);
g.toString(); }