Here is my code for Depth First Search and, as far as I know, it is working fine on most cases. It is not very efficient as I have implemented it for the very first time..
Warning: It is only for bi-directional Graphs or Trees.. And it is not searching anything, just traversing. I think searching should be easy if it is traversing correctly..
def DFS(matrix,x):
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j]=="farigh" or matrix[i][j]=="hogya":
matrix[i].pop()
stack = [x]
Matrix=matrix
print(Matrix)
dimen=len(Matrix)
rslt = [x]
while stack:
current=Matrix[stack[-1]-1]
for j in range(len(current)):
if current[j]==1 :
a=False
if (j+1 not in stack) and (j+1 not in rslt):
stack.append(j+1)
rslt.append(j+1)
print("stack",stack)
a= True
break
if j+1== len(current):
current.append("farigh")
if len(Matrix[stack[-1]-1]) == dimen and a == True :
b=0
current2= Matrix[stack[-1]-1]
for e in range(len(current2)):
if current2[e]==1:
b=b+1
if b==1:
stack.pop()
current2.append("Hogya")
if current[-1]=="farigh":
stack.pop()
print(stack,"stack")
return(rslt,"rslt")
Let me know if you find any bugs.
DFS([[0,0,1],[0,0,1],[1,1,0]], 0)
gives[0, 1, 2]
while I expected[0, 2, 1]
\$\endgroup\$