难度:中等
很简单,从第 0 步开始模拟即可,唯一sb的就是测试用例中如果(0,0)处不为0的话就直接false,而不是去找0在哪
我的代码:
class Solution:
def checkValidGrid(self, grid: List[List[int]]) -> bool:
nx, ny = 0, 0
step = 0
n = len(grid)
if grid[0][0] != 0:
return False
def j(x, y):
if x < 0 or x >= n or y < 0 or y >= n:
return False
if grid[x][y] == step:
return True
return False
while step < len(grid) ** 2 - 1:
step += 1
if j(nx + 1, ny + 2):
nx += 1
ny += 2
continue
if j(nx + 2, ny + 1):
nx += 2
ny += 1
continue
if j(nx + 1, ny - 2):
nx += 1
ny -= 2
continue
if j(nx + 2, ny - 1):
nx += 2
ny -= 1
continue
if j(nx - 1, ny - 2):
nx -= 1
ny -= 2
continue
if j(nx - 2, ny - 1):
nx -= 2
ny -= 1
continue
if j(nx - 2, ny + 1):
nx -= 2
ny += 1
continue
if j(nx - 1, ny + 2):
nx -= 1
ny += 2
continue
return False
return 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)):