Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from itertools import product, starmap
- data = [
- [1, 1, 2, 3, 3, 3, 3, 3],
- [1, 2, 2, 3, 2, 3, 5, 3],
- [1, 4, 2, 2, 2, 5, 5, 3],
- [1, 4, 6, 6, 6, 7, 5, 3],
- [1, 4, 6, 6, 7, 7, 5, 3],
- [1, 4, 4, 8, 7, 7, 5, 5],
- [4, 4, 8, 8, 8, 7, 7, 5],
- [4, 4, 8, 8, 8, 7, 7, 7]
- ]
- regions = [0] * 8
- for i in range(8):
- regions[i] = []
- for i in range(8):
- for j in range(8):
- regions[data[i][j] - 1].append([i, j])
- def count_region(grid, row, col):
- region = regions[data[row][col] - 1]
- count = 0
- for i in range(len(region)):
- cell = region[i]
- if grid[cell[0]][cell[1]] == 2: count += 1
- return count
- def count_neighbors(grid, row, col):
- print("Checking at: " + str(row) + ":" + str(col))
- neighbors = list(starmap(lambda a, b: (row + a, col + b), product((0,-1,+1), (0,-1,+1))))[1:]
- print("... neighbors are: " + str(neighbors))
- count = 0
- for i in range(len(neighbors)):
- cell = neighbors[i]
- if cell[0] < 0 or cell[1] < 0 or cell[0] >= 8 or cell[1] >= 8: continue
- print("Cell is at: " + str(cell[0]) + ":" + str(cell[1]))
- if grid[cell[0]][cell[1]] == 2: count += 1
- return count
- def count_row(grid, row):
- count = 0
- for i in range(8):
- if grid[row][i] == 2: count += 1
- return count
- def count_col(grid, col):
- count = 0
- for i in range(8):
- if grid[i][col] == 2: count += 1
- return count
- def is_safe(grid, row, col, num):
- if count_neighbors(grid, row, col) >= 1: return False
- if count_region(grid, row, col) >= 2: return False
- if count_row(grid, row) >= 2: return False
- if count_col(grid, col) >= 2: return False
- return True
- def find_empty(grid):
- #for i in range(8):
- # if count_col(grid, i) != 2: return False
- # if count_row(grid, i) != 2: return False
- # for j in range(8):
- # if count_neighbors(grid, i, j) != 0: return False
- # cell = regions[i][0]
- # if count_region(grid, cell[0], cell[1]) != 2: return False
- for i in range(8):
- for j in range(8):
- if grid[i][j] == 0: return i, j, True
- return 0, 0, False
- def solve(grid):
- row, col, found = find_empty(grid)
- if found: print("Empty: " + str(row) + ":" + str(col))
- if not found: return True
- for num in range(1, 3):
- print("Trying: " + str(num) + ", " + str(row) + ":" + str(col))
- if is_safe(grid, row, col, num):
- grid[row][col] = num
- if solve(grid):
- return True
- grid[row][col] = 0
- return False
- import sys
- sys.setrecursionlimit(200000000)
- g = [0] * 8
- for i in range(8):
- g[i] = [0] * 8
- solve(g)
- for i in range(8):
- print(g[i])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement