1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| """ 2048合并规则: 1. 相邻会碰撞的两个相同数字合并且只会触发一次合并; 2. 优先合并移动方向顶部的位置,比如 [2, 2 ,2 , 2] 行向右合并为 [0, 0, 4, 4] 输入: 第1行是2048块的滑动方向键。1:上、2:下、3:左、4:右。 接下来4 x 4的数字矩阵用空格分割,0表示该位置没有数字。 输出: 用户按下房间键红后的矩阵值。
示例 输入: 1 0 0 0 2 0 0 0 2 0 0 4 8 0 0 4 8 输出: 0 0 8 4 0 0 0 16 0 0 0 0 0 0 0 0 """
def MoveUp(): for j in range(0, 4): for i in range(0, 3): if Num[i][j] != 0: continue for k in range(i+1, 4): if Num[k][j] != 0: Num[i][j], Num[k][j] = Num[k][j], Num[i][j] break
def MoveDown(): for j in range(0, 4): for i in range(3, 0, -1): if Num[i][j] != 0: continue for k in range(i-1, -1, -1): if Num[k][j] != 0: Num[i][j], Num[k][j] = Num[k][j], Num[i][j] break
def MoveLeft(): for i in range(0, 4): for j in range(0, 3): if Num[i][j] != 0: continue for k in range(j+1, 4): if Num[i][k] != 0: Num[i][j], Num[i][k] = Num[i][k], Num[i][j] break
def MoveRight(): for i in range(0, 4): for j in range(3, 0, -1): if Num[i][j] != 0: continue for k in range(j-1, -1, -1): if Num[i][k] != 0: Num[i][j], Num[i][k] = Num[i][k], Num[i][j] break
def move(direction): if direction == 1: MoveUp() for i in range(0, 3): for j in range(0, 4): if Num[i][j] == Num[i + 1][j]: Num[i][j] <<= 1 Num[i + 1][j] = 0 MoveUp() elif direction == 2: MoveDown() for i in range(3, 0, -1): for j in range(0, 4): if Num[i][j] == Num[i - 1][j]: Num[i][j] <<= 1 Num[i - 1][j] = 0 MoveDown() elif direction == 3: MoveRight() for i in range(0, 4): for j in range(3, 0, -1): if Num[i][j] == Num[i][j - 1]: Num[i][j] <<= 1 Num[i][j - 1] = 0 MoveRight() else: MoveLeft() for i in range(0, 4): for j in range(0, 3): if Num[i][j] == Num[i][j - 1]: Num[i][j] <<= 1 Num[i][j - 1] = 0 MoveLeft()
if __name__=="__main__": direction = int(input()) Num = [[] for i in range(4)] for i in range(4): Num[i] = list(map(int, input().strip().split())) move(direction) print(Num)
|