15-112 Fundamentals of Programming

Notes - Lecture 5.5


Content

  1. floodFill (grid-based)
  2. Backtracking
    1. nQueens

1. floodFill

Python code: floodFillGrid.py
Key excerpt:
def floodFill(data, row, col, depth=0):
    if ((row < 0) or (row >= data.rows) or
        (col < 0) or (col >= data.cols)):
        return # off-board!
    cell = data.cells[row][col]
    if (cell.isWall == True):
        return # hit a wall
    if (cell.depth >= 0):
        return # already been here

    # "fill" this cell
    cell.depth = depth
    cell.ordinal = len(data.floodFillOrder)
    data.floodFillOrder.append(cell)

    # then recursively fill its neighbors
    floodFill(data, row-1, col,   depth+1)
    floodFill(data, row+1, col,   depth+1)
    floodFill(data, row,   col-1, depth+1)
    floodFill(data, row,   col+1, depth+1)

2. Backtracking

1. nQueens

Python code: nQueens.py
Key excerpt:
def solve(n, m, constraints):
    if(m == 0):
        return []       
    for row in range(n):
        if (isLegal(row, constraints)):         
            newConstraints = constraints + [row]            
            result = solve(n, m-1, newConstraints)
            if (result != False):
                return [row] + result
    return False


Valid CSS! Valid XHTML 1.0 Strict