Knight Tour

less than 1 minute read

def knightTour(nlevel,vertex,limit,path):
	vertex.setColor("visited")
	path.append(vertex)
	

	if nlevel < limit:
		connectedlists = vertex.getConnections()
		i = 0
		done = False
		while i < len(connectedlists) and not done:
			if nbrvertex[i].getColor() =='not visited':
				knightTour(nlevle+1,nbrvertex[i],limit,path)
			i = i +1

		if not done:
			path.pop()
			vertex.setColor("not visited")
	else:
		done = True 

	return done

class Vertex:

	def __init__(self,key):
		self.id = key
		self.connectedto = {}
		self.color = 'not visited'
		
	def addConnection(self,nbkey,cost):
		 if not nbkey in self.connectedto.keys():
			self.connectedto[nbkey] = cost


class Graph:

	def __init__(self):
		self.vertexlist = {}
		self.numvertex = 0		

	def addVertex(self,key):
		self.numvertex += 1
		self.vertexlist[key] = Vertex(key)

	def addEdge(self,s1key,s2key,cost):
		
		if not s1key in self.vertexlist.keys():
			self.addVertex(s1key)
		if not s2key in self.vertexlist.keys():
			self.addVertex(s2key)

		self.vertexlist[s1key].addConnection(nbkey,cost)