I was asked a few weeks ago, to find all the different and unique ways to reach the top right of a chess board, with x, y > 3, starting from (0, 0), knowing that you can only increase x and y by +1.
I still haven't been able to find algorithms that would explain how to navigate over a chessboard, so I was wondering if you guys had anything to recommend ?
In other words :
How would you list all the unique ways to reach the top right (x, y) of a chessboard with a pin, starting from bottom left (0, 0). You can only move your pin up or right ?
#Update 10/16/2010 :
Okay so I did a bit of research in DFS, and wasn't sure where to start from, and then looked up PreOrder Traversal of a Tree, and I came up with this, since basically a chessboard is a tree :
#!/usr/bin/python
class Node(object):
value = None
left = None
right = None
def SetValue(self, value):
self.value = value
def SetLeftNode(self, node):
self.left = node
def SetRightNode(self, node):
self.right = node
def main():
a = Node()
a.SetValue((0,0))
b = Node()
b.SetValue((1,0))
c = Node()
c.SetValue((2,0))
d = Node()
d.SetValue((0,1))
e = Node()
e.SetValue((1,1))
f = Node()
f.SetValue((2,1))
g = Node()
g.SetValue((0,2))
h = Node()
h.SetValue((1,2))
i = Node()
i.SetValue((2,2))
a.SetLeftNode(b)
a.SetRightNode(d)
b.SetLeftNode(g)
b.SetRightNode(e)
c.SetLeftNode(f)
c.SetRightNode(None)
d.SetLeftNode(e)
d.SetRightNode(c)
e.SetLeftNode(h)
e.SetRightNode(f)
f.SetLeftNode(i)
f.SetRightNode(None)
g.SetLeftNode(None)
g.SetRightNode(h)
h.SetLeftNode(None)
h.SetRightNode(i)
i.SetLeftNode(None)
i.SetRightNode(None)
PreOrderTraversal(a)
def PreOrderTraversal(node):
if not node:
return None
print node.value
if node.value == (2,2):
print 'Reached i'
PreOrderTraversal(node.left)
PreOrderTraversal(node.right)
main()
The output of this is the following :
(0, 0)
(1, 0)
(0, 2)
(1, 2)
(2, 2)
Reached i
(1, 1)
(1, 2)
(2, 2)
Reached i
(2, 1)
(2, 2)
Reached i
(0, 1)
(1, 1)
(1, 2)
(2, 2)
Reached i
(2, 1)
(2, 2)
Reached i
(2, 0)
(2, 1)
(2, 2)
Reached i
It definitely goes through all the unique path, but I am sure there's a way to improve this to actually print out the complete path. For some reason I can't find a way to do this using recursion. Any idea ?