算法-找出井字棋的获胜者

# 找出井字棋的获胜者

来源: https://leetcode.cn/problems/find-winner-on-a-tic-tac-toe-game/ (opens new window)

A 和 B 在一个 3 x 3 的网格上玩井字棋。给你一个数组 moves,其中每个元素是大小为 2 的另一个数组(元素分别对应网格的行和列),它按照 A 和 B 的行动顺序(先 A 后 B)记录了两人各自的棋子位置。如果游戏存在获胜者(A 或 B),就返回该游戏的获胜者;如果游戏以平局结束,则返回 "Draw";如果仍会有行动(游戏未结束),则返回 "Pending"。假设 moves 都 有效(遵循井字棋规则),网格最初是空的, A 将先行动

解题思路:

  1. 先模拟一个棋盘, 将玩家的路线找坐标进行填充, 这样就知道每个玩家在棋盘的位置

  2. 设定好棋盘取胜的线(共8种), 再进行坐标和取胜位置的匹配即可

点击查看代码













































 




 














/**
 * 找出井字棋的获胜者
 * --------|-------|--------
 * | (0,0) | (0,1) | (0,2) |
 * --------|-------|--------
 * | (1,0) | (1,1) | (1,2) |
 * --------|-------|--------
 * | (2,0) | (2,1) | (2,2) |
 * --------|-------|--------
 * 
 * 获胜路线的坐标
 * [
 *  [0,0], [0,1], [0,2],
 *  [1,0], [1,1], [1,2],
 *  [2,0], [2,1], [2,2],
 *  [0,0], [1,0], [2,0],
 *  [0,1], [1,1], [2,2],
 *  [0,2], [1,2], [2,2],
 *  [0,0], [1,1], [2,2],
 *  [0,2], [1,1], [2,0],
 * ]
 * 
 * @param {*} moves 
 * @returns {string}
 */
const TicTacToe = (moves) => {
  // 获胜线
  const winLines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  let player = 'A';
  // 模拟棋盘
  const playerLines = Array.from({ length: 3 }, () =>
    Array.from({ length: 3 }, () => null));
  player = moves.length % 2 === 1 ? 'A' : 'B'
  moves.forEach(([x, y], i) => {
    const role = i % 2 === 0 ? 'A' : 'B'
    // 记录玩家的坐标
    playerLines[x][y] = role
  })
  const lines = playerLines.flat()
  for (let i = 0; i < winLines.length; i++) {
    const [a, b, c] = winLines[i]
    if (lines[a] && lines[a] === lines[b] && lines[a] === lines[c])
      return lines[a]
  }
  return moves.length === 9 ? 'Draw' : 'Pending'
}

const Amoves = [[0, 0], [2, 0], [1, 1], [2, 1], [2, 2]]
const Bmoves = [[0, 0], [1, 1], [0, 1], [0, 2], [1, 0], [2, 0]]
const DrawMoves = [[0, 0], [1, 1], [2, 0], [1, 0], [1, 2], [2, 1], [0, 1], [0, 2], [2, 2]]
const PendingMoves = [[0, 0], [1, 1]]
console.log('It will be expected: A', TicTacToe(Amoves)) // 'A'
console.log('It will be expected: B', TicTacToe(Bmoves)) // 'B'
console.log('It will be expected: Draw', TicTacToe(DrawMoves)) // 'Draw'
console.log('It will be expected: Pending', TicTacToe(PendingMoves)) // 'Pending'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64