前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >2021-11-09:设计井字棋。谁先同行或者同列都是自己的棋子,就算获得胜利 。力扣348。

2021-11-09:设计井字棋。谁先同行或者同列都是自己的棋子,就算获得胜利 。力扣348。

作者头像
福大大架构师每日一题
发布2021-11-16 10:31:57
2340
发布2021-11-16 10:31:57
举报
文章被收录于专栏:福大大架构师每日一题

2021-11-09:设计井字棋。谁先同行或者同列都是自己的棋子,就算获得胜利 。力扣348。

答案2021-11-09:

记录n行,n列,对角线的某个棋手的棋子数量。

代码用golang编写。代码如下:

代码语言:javascript
复制
package main

import "fmt"

func main() {
    nttt := NewTicTacToe(3)
    fmt.Println(nttt.move(0, 0, 1))
    fmt.Println(nttt.move(1, 0, 1))
    fmt.Println(nttt.move(2, 0, 1))
}

type TicTacToe struct {
    rows    [][]int
    cols    [][]int
    leftUp  []int
    rightUp []int
    matrix  [][]bool
    N       int
}

func NewTicTacToe(n int) *TicTacToe {
    res := &TicTacToe{}
    // rows[a][1] : 1这个人,在a行上,下了几个
    // rows[b][2] : 2这个人,在b行上,下了几个
    //rows = new int[n][3]; //0 1 2
    res.rows = make([][]int, n)
    for i := 0; i < n; i++ {
        res.rows[i] = make([]int, 3)
    }

    res.cols = make([][]int, n)
    for i := 0; i < n; i++ {
        res.cols[i] = make([]int, 3)
    }
    // leftUp[2] = 7 : 2这个人,在左对角线上,下了7个
    res.leftUp = make([]int, 3)
    // rightUp[1] = 9 : 1这个人,在右对角线上,下了9个
    res.rightUp = make([]int, 3)
    res.matrix = make([][]bool, n)
    for i := 0; i < n; i++ {
        res.matrix[i] = make([]bool, n)
    }
    res.N = n
    return res
}

func (this *TicTacToe) move(row, col, player int) int {
    if this.matrix[row][col] {
        return 0
    }
    this.matrix[row][col] = true
    this.rows[row][player]++
    this.cols[col][player]++
    if row == col {
        this.leftUp[player]++
    }
    if row+col == this.N-1 {
        this.rightUp[player]++
    }
    if this.rows[row][player] == this.N || this.cols[col][player] == this.N || this.leftUp[player] == this.N || this.rightUp[player] == this.N {
        return player
    }
    return 0
}

执行结果如下:

[左神java代码](https://github.com/algorithmzuo/coding-for-great-offer/blob/main/src/class34/Problem_0348_DesignTicTacToe.java)

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-11-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 福大大架构师每日一题 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档