检查二维列表中的对角线(Python) [英] checking diagonals in 2d list (Python)

查看:42
本文介绍了检查二维列表中的对角线(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初的问题:对于给定的 3x3 井字棋盘,检查是否有玩家赢了.

The initial problem: for a given 3x3 tic tac toe board check if one of the players has won.

到目前为止,我提出的最简单的解决方案是旋转矩阵并对每一行求和:

The simplest solution I have come up so far is rotating the matrix and summing up each row:

board
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]

pr(board)
0 1 2
3 4 5
6 7 8

pr(zip(*board))
0 3 6
1 4 7
2 5 8

上面的 0..9 数字仅用于显示棋盘上的位置,通常它们会填充 1 代表玩家 1,填充 -1 代表玩家 2 和 0 表示未填充的位置.逐行进行,如果总和为 3 或 -3,则这是获胜块.

0..9 numbers above are just for showing positions on the board, normally they would be filled with 1 for player 1 and -1 for player 2 and 0 for unfilled position. Go row by row and if it sums up to 3 or -3 this is the winning block.

但是,不检查对角线.有没有办法以优雅+高性能的方式从这样的矩阵中提取对角线?我的意思不是手动"使用琐碎的索引(0、1、2),而是获取 n x n 矩阵的对角线.

However, diagonals are not checked. Is there some way to extract diagonals from such matrix in elegant + highly performant way? I don't mean using trivial indexes "manually" (0, 1, 2), but rather get diagonal of n x n matrix.

附言pr 只是打印二维列表的辅助函数:

P.S. pr is just a helper function for printing 2d list:

def pr(x):
    for row in x:
        print ' '.join(map(str, row))

推荐答案

用魔方为您的游戏场地编号

Number your game field with a magic square

2|9|4
7|5|3
6|1|8

现在在三步后求和并检查总和是否为 15 --> 获胜者.您必须为每个玩家检查这一点.当然你必须在第 4 步和第 5 步后重新检查(仅限开始游戏的玩家)

Now sum up after three moves and check if the sum is 15 --> Winner. You have to check this for every player. Surely you have to recheck after 4th move and 5th move (only the player that started the game)

这就是我在我的第一个 Java 课程中解决这个问题的方法.

This is how I solved this problem in my first Java class.

这篇关于检查二维列表中的对角线(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆