--- id: 6a22d77ddf034bc4e35b1d5d title: "Challenge 356: Magic Square Solver" challengeType: 29 dashedName: challenge-356 --- # --description-- Given a 3x3 grid with one missing number (represented as `0`), return the missing number that completes the magic square, or `"impossible"` if no valid number exists. A magic square is a grid where every row, column, and diagonal adds up to the same number. # --hints-- `solve_magic_square([[2, 7, 6], [9, 0, 1], [4, 3, 8]])` should return `5`. ```js ({test: () => { runPython(` from unittest import TestCase TestCase().assertEqual(solve_magic_square([[2, 7, 6], [9, 0, 1], [4, 3, 8]]), 5)`) }}) ``` `solve_magic_square([[0, 14, 12], [18, 10, 2], [8, 6, 16]])` should return `4`. ```js ({test: () => { runPython(` from unittest import TestCase TestCase().assertEqual(solve_magic_square([[0, 14, 12], [18, 10, 2], [8, 6, 16]]), 4)`) }}) ``` `solve_magic_square([[12, 17, 16], [19, 0, 10], [14, 13, 18]])` should return `"impossible"`. ```js ({test: () => { runPython(` from unittest import TestCase TestCase().assertEqual(solve_magic_square([[12, 17, 16], [19, 0, 10], [14, 13, 18]]), "impossible")`) }}) ``` `solve_magic_square([[15, 35, 31], [43, 27, 11], [23, 19, 0]])` should return `39`. ```js ({test: () => { runPython(` from unittest import TestCase TestCase().assertEqual(solve_magic_square([[15, 35, 31], [43, 27, 11], [23, 19, 0]]), 39)`) }}) ``` `solve_magic_square([[26, 41, 14], [47, 35, 0], [32, 29, 44]])` should return `"impossible"`. ```js ({test: () => { runPython(` from unittest import TestCase TestCase().assertEqual(solve_magic_square([[26, 41, 14], [47, 35, 0], [32, 29, 44]]), "impossible")`) }}) ``` # --seed-- ## --seed-contents-- ```py def solve_magic_square(grid): return grid ``` # --solutions-- ```py def solve_magic_square(grid): flat = [n for row in grid for n in row] zero_index = flat.index(0) row = zero_index // 3 col = zero_index % 3 target = next(sum(r) for r in grid if 0 not in r) missing = target - sum(grid[row]) filled = [r[:] for r in grid] filled[row][col] = missing def check(arr): return sum(arr) == target for i in range(3): if not check(filled[i]): return "impossible" if not check([filled[r][i] for r in range(3)]): return "impossible" if not check([filled[0][0], filled[1][1], filled[2][2]]): return "impossible" if not check([filled[0][2], filled[1][1], filled[2][0]]): return "impossible" return missing ```