A 和 B 在一个 3 x 3 的网格上玩井字棋。
井字棋游戏的规则如下:
玩家轮流将棋子放在空方格 (" ") 上。
第一个玩家 A 总是用 “X” 作为棋子,而第二个玩家 B 总是用 “O” 作为棋子。
“X” 和 “O” 只能放在空方格中,而不能放在已经被占用的方格上。
只要有 3 个相同的(非空)棋子排成一条直线(行、列、对角线)时,游戏结束。
如果所有方块都放满棋子(不为空),游戏也会结束。
游戏结束后,棋子无法再进行任何移动。
给你一个数组 moves,其中每个元素是大小为 2 的另一个数组(元素分别对应网格的行和列),它按照 A 和 B 的行动顺序(先 A 后 B)记录了两人各自的棋子位置。
如果游戏存在获胜者(A 或 B),就返回该游戏的获胜者;如果游戏以平局结束,则返回 “Draw”;如果仍会有行动(游戏未结束),则返回 “Pending”。
你可以假设 moves 都 有效(遵循井字棋规则),网格最初是空的,A 将先行动。
Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are:
Players take turns placing characters into empty squares ’ '.
The first player A always places ‘X’ characters, while the second player B always places ‘O’ characters.
‘X’ and ‘O’ characters are always placed into empty squares, never on filled ones.
The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.
The game also ends if all squares are non-empty.
No more moves can be played if the game is over.
Given a 2D integer array moves where moves[i] = [rowi, coli] indicates that the ith move will be played on grid[rowi][coli]. return the winner of the game if it exists (A or B). In case the game ends in a draw return “Draw”. If there are still movements to play return “Pending”.
You can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe), the grid is initially empty, and A will play first.
示例 1:
输入:moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
输出:"A"
解释:"A" 获胜,他总是先走。
"X " "X " "X " "X " "X "
" " -> " " -> " X " -> " X " -> " X "
" " "O " "O " "OO " "OOX"
示例 2:
输入:moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]
输出:"B"
解释:"B" 获胜。
"X " "X " "XX " "XXO" "XXO" "XXO"
" " -> " O " -> " O " -> " O " -> "XO " -> "XO "
" " " " " " " " " " "O "
示例 3:
输入:moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]
输出:"Draw"
输出:由于没有办法再行动,游戏以平局结束。
"XXO"
"OOX"
"XOX"
示例 4:
输入:moves = [[0,0],[1,1]]
输出:"Pending"
解释:游戏还没有结束。
"X "
" O "
" "
首先创建一个3行3列用0填充的数组
根据A先下的规则,moves下标可以被2整除,将此时的位置替换成B,否则替换成A
3行3列-
- 遍历每行,出现一行数据都相等的时候,返回该行的第一个值进行返回
- 遍历每列,出现一列数据都相等的时候,返回该列的第一个值进行返回
- 再遍历斜对角,都相等的时候,返回
- 当moves的长度小于9的时候,没下完返回Pending
- 其他时候,平局返回,Draw
var tictactoe = function (moves) {
const ans = new Array(3).fill(0).map(() => new Array(3).fill(0));
moves.forEach((item, index) => {
let [x, y] = item
ans[x][y] = index % 2 ? 'B' : 'A'
})
for (let i = 0; i < 3; i++) {
let [a, b, c] = ans[i]
if (a && a == b && b == c) return a
}
for (let j = 0; j < 3; j++) {
let [a, b, c] = [ans[0][j], ans[1][j], ans[2][j]]
if (a && a == b && b == c) return a
}
let [a, b, c] = [ans[0][0], ans[1][1], ans[2][2]]
if (a && a == b && b == c) return a
let [d, e, f] = [ans[2][0], ans[1][1], ans[0][2]]
if (d && d == e && e == f) return d
if (moves.length < 9) return 'Pending'
return 'Draw'
};
leetcode:https://leetcode.cn/problems/find-winner-on-a-tic-tac-toe-game/