Skip to content

Instantly share code, notes, and snippets.

@josiahcoad
Created October 28, 2022 16:24
Show Gist options
  • Save josiahcoad/777b87c63782ac08be91ab32c6d175b2 to your computer and use it in GitHub Desktop.
Save josiahcoad/777b87c63782ac08be91ab32c6d175b2 to your computer and use it in GitHub Desktop.
def get_adjacent_matrices(matrix: Matrix, empty_tile: Tuple[int, int] = None) -> List[Matrix]:
def find_empty_tile(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == 0:
return (i, j)
if empty_tile is None:
empty_tile = find_empty_tile(matrix)
def get_candidates(row: int, col: int) -> List[Tuple[int, int]]:
"""
ex 1, 1 => [(0, 1), (2, 1), (1, 0), (1, 2)]
"""
return [(row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1)]
def filter_candidates(candidates: List[Matrix]) -> List[Matrix]:
"""
matrix = [[1, 2], [3, 0]]
ex [(0, 1), (2, 1), (1, 0), (1, 2)] -> [(0, 1), (1, 0)]
"""
new_list = []
for (i, j) in candidates:
if i < len(matrix) and i >= 0 and j < len(matrix[i]) and j >= 0:
new_list.append((i, j))
return new_list
row_empty, col_empty = empty_tile
candidates = get_candidates(row_empty, col_empty)
new_empty_tiles = filter_candidates(candidates)
neighbors = []
for new_empty_tile in new_empty_tiles:
neighbor = move_empty_tile(matrix, empty_tile, new_empty_tile)
neighbors.append(neighbor)
return neighbors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment