给定一个二维数组board,代表棋盘,其中元素为1的代表是当前玩家的棋子,0表示没有棋子,-1代表是对方玩家的棋子。当一方棋子在横竖斜方向上有连成排的及获胜(及井字棋规则),返回当前玩家是否胜出。
测试样例:
[[1,0,1],[1,-1,-1],[1,-1,0]]
返回:true
def checkWon(self, board): for i in range(len(board)): if sum(board[i]) == len(board): return 'true' elif sum([board[j][i] for j in range(len(board))]) == len(board): return 'true' if sum([board[i][i] for i in range(len(board))]) == len(board): return 'true' if sum([board[i][len(board)-1-i] for i in range(len(board))]) == len(board): return 'true' return 'false'
# -*- coding:utf-8 -*- class Board: def checkWon(self, board): if not board: return False b = board n = len(b) # 检查行,列 for i in range(n): target = [1] * n if board[i] == target: return True if [j[i] for j in board] == target: return True # 对角线, 逆对角线 sum = ssum = 0 for i in range(n): if b[i][i] == 1: sum += 1 if b[n-i-1][i] == 1: ssum += 1 if sum == n or ssum ==n: return True return False