难度:中等
很简单,从第 0 步开始模拟即可,唯一sb的就是测试用例中如果(0,0)处不为0的话就直接false,而不是去找0在哪
我的代码:
class Solution:def checkValidGrid(self, grid: List[List[int]]) -> bool:nx, ny = 0, 0step = 0n = len(grid)if grid[0][0] != 0:return Falsedef j(x, y):if x < 0 or x >= n or y < 0 or y >= n:return Falseif grid[x][y] == step:return Truereturn Falsewhile step < len(grid) ** 2 - 1:step += 1if j(nx + 1, ny + 2):nx += 1ny += 2continueif j(nx + 2, ny + 1):nx += 2ny += 1continueif j(nx + 1, ny - 2):nx += 1ny -= 2continueif j(nx + 2, ny - 1):nx += 2ny -= 1continueif j(nx - 1, ny - 2):nx -= 1ny -= 2continueif j(nx - 2, ny - 1):nx -= 2ny -= 1continueif j(nx - 2, ny + 1):nx -= 2ny += 1continueif j(nx - 1, ny + 2):nx -= 1ny += 2continuereturn Falsereturn True
最好还是单独列出行动方式,而不是写多个if判断
directions = [[-2, 1],[-2, -1],[2, 1],[2, -1],[1, 2],[1, -2],[-1, 2],[-1, -2]
]
#或者这样
for j in ((-2,-1),(-2,1),(-1,2),(-1,-2),(1,2),(1,-2),(2,1),(2,-1)):