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

答案2021-11-09:

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

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

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行上,下了几个
    // row***][2] : 2这个人,在b行上,下了几个
    //rows = new int[n][3]; //0 1 2
    res.row***ake([][]int, n)
    for i := 0; i < n; i++ {
        res.rows[i] = make([]int, 3)
    }

    res.col***ake([][]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)
    re***atrix = make([][]bool, n)
    for i := 0; i < n; i++ {
        re***atrix[i] = make([]bool, n)
    }
    res.N = n
    return res
}

func (this *TicTacToe) move(row, col, player int) int {
    if thi***atrix[row][col] {
        return 0
    }
    thi***atrix[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代码