Код: Выделить всё
grid1 = [
[11, 12, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[11, 12, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[11, 12, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[11, 12, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[11, 0, 11, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[11, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];
grid2 = [
[11, 12, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[11, 12, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[11, 12, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[11, 12, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[11, 0, 11, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[11, 11, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];
def find_last_snake_tail(grid):
rows = len(grid)
cols = len(grid[0])
snake_paths = []
current_path = []
for j in range(cols):
if grid[0][j] != 0:
head = grid[0][j]
i = 0
j_start = j
while i < rows and grid[i][j_start] == head:
current_path.append((i, j_start))
i += 1
if i == rows:
j_start += 1
while j < cols and grid[i-1][j_start] == head:
current_path.append((i-1, j_start))
j_start += 1
snake_paths.append(current_path)
current_path = []
last_snake_tail = snake_paths[-1][-1]
return last_snake_tail
print(find_last_snake_tail(grid1))
print(find_last_snake_tail(grid2))
print(find_last_snake_tail(grid3))
- the grid is init by 6*15 and filled with 0
- there will be a for-loop looping another 2d array and compare the element with ceterin logic
- 11 means the comparison is equals and 12 mens the comparison is not equals
- then the program will insert the comparison result (11/12) into the grid base on the find_last_snake_tail
- if the current comparison result is same with the last insert result, it will add to new row with same cell position, till it reach row 6 and it will kept growing rightwards.
- if the current comparison result is not same with the last insert result, it will start a new root on row 1 new cells (next to the old snake root)
- also the program will base on the find_last_snake_tail location to controll when the snake grow downwards or rightwards
- after the comparison completed, the program will base on the grid to render a table in the ui
grid1 actual result: (4, 2)
grid1 expect result: (4, 3)
grid2 actual result: (4, 2)
grid2 expect result: (5, 3)
Источник: https://stackoverflow.com/questions/781 ... a-2d-array