首页 > 试题广场 >

井字棋

[编程题]井字棋
  • 热度指数:9472 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

给定一个二维数组board,代表棋盘,其中元素为1的代表是当前玩家的棋子,0表示没有棋子,-1代表是对方玩家的棋子。当一方棋子在横竖斜方向上有连成排的及获胜(及井字棋规则),返回当前玩家是否胜出。

测试样例:
[[1,0,1],[1,-1,-1],[1,-1,0]]
返回:true
我的解法是不是太憨了,直接穷举 😄😄😄 
class Board:
    def checkWon(self, board):
        # write code here
        if  ((board[0][0] == 1 and board[0][1] == 1 and board[0][2] == 1) or 
           (board[1][0] == 1 and board[1][1] == 1 and board[1][2] == 1) or 
           (board[2][0] == 1 and board[2][1] == 1 and board[2][2] == 1) or 
           (board[0][0] == 1 and board[1][0] == 1 and board[2][0] == 1) or 
           (board[0][1] == 1 and board[1][1] == 1 and board[2][1] == 1) or 
           (board[0][2] == 1 and board[1][2] == 1 and board[2][2] == 1) or 
           (board[0][0] == 1 and board[1][1] == 1 and board[2][2] == 1) or 
           (board[0][2] == 1 and board[1][1] == 1 and board[2][0] == 1) ) :
            return True
        else:
            return False

发表于 2021-11-30 22:20:23 回复(0)
为啥在IDLE上先实的false,在这里运行是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'


发表于 2020-08-21 15:07:34 回复(1)

python 一行解法

    def checkWon(self, board):
        return sum(map(lambda c:c.count(1),board))>sum(map(lambda c:c.count(-1),board))
发表于 2017-10-31 18:18:56 回复(2)
计算和就可以
# -*- 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
        

发表于 2016-08-09 11:27:12 回复(0)