Skip to content

Instantly share code, notes, and snippets.

@SuryaSankar
Created April 30, 2015 05:46
Show Gist options
  • Save SuryaSankar/aae1e681ad7517d5d594 to your computer and use it in GitHub Desktop.
Save SuryaSankar/aae1e681ad7517d5d594 to your computer and use it in GitHub Desktop.
All paths in a rowxcol grid from top left till bottom right
class Point(object):
def __init__(self, row, col):
self.row = row
self.col = col
def __eq__(self, other):
return self.row == other.row and self.col == other.col
def __repr__(self):
return "(%s, %s)" % (self.row, self.col)
class Grid(object):
def __init__(self, no_of_rows, no_of_cols):
self.no_of_cols = no_of_cols
self.no_of_rows = no_of_rows
self.top_left_point = Point(1, 1)
self.bottom_left_point = Point(no_of_rows, no_of_cols)
def right(self, point):
if point.col == self.no_of_cols:
return None
return Point(row=point.row, col=point.col + 1)
def down(self, point):
if point.row == self.no_of_rows:
return None
return Point(row=point.row + 1, col=point.col)
def trace_paths_to_bottom_right(self, point):
if point == self.bottom_left_point:
return [[point]]
rpoint = self.right(point)
dpoint = self.down(point)
paths = []
if rpoint:
for path in self.trace_paths_to_bottom_right(rpoint):
path.insert(0, point)
paths.append(path)
if dpoint:
for path in self.trace_paths_to_bottom_right(dpoint):
path.insert(0, point)
paths.append(path)
return paths
if __name__ == '__main__':
grid = Grid(3, 3)
print grid.trace_paths_to_bottom_right(grid.top_left_point)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment