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))
網格初始化為6*15,填入0
將有一個 for 迴圈去迴圈另一個二維陣列並將元素與其他邏輯進行比較
11表示比較相等,12表示比較不等於
然後程式會將比較結果(11/12)插入find_last_snake_tail上的網格中
如果目前比較結果與上次插入結果相同,則會新增至相同儲存格位置的新行,直到到達第6行,並繼續向右增長。
如果目前比較結果與上次插入結果不同,則會在第1行新單元格上開始一個新根(在舊蛇根旁邊)
程式也會根據find_last_snake_tail位置來控制蛇何時向下或向右生長
比較完成後,程式會根據網格在ui中渲染出一個表格
無法從上面的這些變數(grid1,grid2)獲得預期結果
grid1 實際結果:(4, 2) grid1 期望結果:(4, 3)
grid2 實際結果:(4, 2) grid2 期望結果:(5, 3)