Re: [闲聊] 每日leetcode

楼主: JerryChungYC (JerryChung)   2024-08-09 10:43:45
https://leetcode.com/problems/magic-squares-in-grid
840. Magic Squares In Grid
找出由1~9组成的3*3矩阵且每个行、列、斜都是15的数量
Python Code:
class Solution:
def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
result = 0
check = {1, 2, 3, 4, 5, 6, 7, 8, 9}
for i, v in enumerate(grid):
idx = 0
while 5 in v[idx+1:] and i not in {0, len(grid)-1}:
idx = v.index(5, idx+1)
if idx in {0, len(v)-1}:
continue
if not set([grid[i-1][idx],grid[i-1][idx-1],grid[i-1][idx+1],
grid[i+1][idx],grid[i+1][idx-1],grid[i+1][idx+1],
v[idx], v[idx-1], v[idx+1]]) == check:
continue
if all([
sum(v[idx-1:idx+2]) == 15,
sum(grid[i-1][idx-1:idx+2]) == 15,
sum(grid[i+1][idx-1:idx+2]) == 15,
sum([v[idx], grid[i-1][idx], grid[i+1][idx]]) == 15,
sum([v[idx-1], grid[i-1][idx-1], grid[i+1][idx-1]]) == 15,
sum([v[idx+1], grid[i-1][idx+1], grid[i+1][idx+1]]) == 15,
sum([grid[i-1][idx-1], v[idx], grid[i+1][idx+1]]) == 15,
sum([grid[i+1][idx-1], v[idx], grid[i-1][idx+1]]) == 15
]):
result += 1
return result
照直觉写的 懒得改了
作者: sustainer123 (caster)   2024-08-09 10:47:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com