刚开始也是90%,后来发现有个边界出了问题,改完就ac了 def up(a): # 向上合并, 1 for i in range(3): for j in range(4): if a[i][j] == a[i + 1][j]: a[i][j] = 2*a[i][j] a[i + 1][j] = 0 for j in range(4): idxs = [] for i in range(4): if a[i][j] == 0: idxs.append(i) elif a[i][j] != 0 and len(idxs) >0: idx = idxs.pop(0) a[i][j],a[idx][j] = a[idx][j],a[i][j] idxs.append(i) return a def low(a): # 向下合并, 2 for i in range(3,0,-1): for j in range(4): if a[i][j] == a[i - 1][j]: a[i][j] = 2*a[i][j] a[i - 1][j] = 0 for j in range(4): idxs = [] for i in range(3,-1,-1): if a[i][j] == 0: idxs.append(i) elif a[i][j] != 0 and len(idxs) >0: idx = idxs.pop(0) a[i][j],a[idx][j] = a[idx][j],a[i][j] idxs.append(i) return a def left(a): #向左合并, 3 for i in range(4): for j in range(3): if a[i][j] == a[i][j+1]: a[i][j] = 2*a[i][j] a[i][j+1] =0 # 去除0 for i in range(4): idxs = [] for j in range(4): if a[i][j] == 0: idxs.append(j) elif a[i][j] != 0 and len(idxs) >0: idx = idxs.pop(0) a[i][j],a[i][idx] = a[i][idx],a[i][j] idxs.append(j) return a def right(a): for i in range(4): for j in range(3,0,-1): if a[i][j] == a[i][j-1]: a[i][j] = 2*a[i][j] a[i][j-1] =0 #去零 for i in range(4): idxs = [] for j in range(3,-1,-1): if a[i][j] == 0: idxs.append(j) elif a[i][j] != 0 and len(idxs) >0: idx = idxs.pop(0) a[i][j],a[i][idx] = a[i][idx],a[i][j] idxs.append(j) return a dx = int(input()) a = [] for _ in range(4): a.append(list(map(int, input().split()))) if dx == 1: res = up(a) elif dx ==2: res = low(a) elif dx ==3: res = left(a) elif dx == 4: res = right(a) for item in res: print(' '.join('%s' %i for i in item))
点赞 评论

相关推荐

点赞 评论 收藏
分享
牛客网
牛客企业服务