qidao123.com技术社区-IT企服评测·应用市场

标题: LeetCode1275 [打印本页]

作者: 饭宝    时间: 2025-5-4 05:30
标题: LeetCode1275
LeetCode1275

目次



题目形貌

给定一个 3x3 的井字棋棋盘,moves 数组表示玩家的落子次序,其中 moves = [row, col] 表示第 i 步落子的位置。玩家 A 先手,玩家 B 后手。你必要根据 moves 判断游戏的胜负环境。
返回值:


示例

示例 1

输入:
  1. moves = [[0, 0], [2, 0], [1, 1], [2, 1], [2, 2]]
复制代码
输出:
  1. "A"
复制代码
解释:


示例 2

输入:
  1. moves = [[0, 0], [1, 1], [0, 1], [0, 2], [1, 0], [2, 0]]
复制代码
输出:
  1. "B"
复制代码
解释:


示例 3

输入:
  1. moves = [[0, 0], [1, 1], [2, 0], [1, 0], [1, 2], [2, 1], [0, 1], [0, 2], [2, 2]]
复制代码
输出:
  1. "Draw"
复制代码
解释:


思路分析

题目核心

我们必要根据玩家的落子次序,判断游戏的胜负环境。
思路拆解


代码段

  1. class Solution {    public String tictactoe(int[][] moves) {        int len = moves.length;        int[] dp = moves[len - 1];        int x = 0, y = 0, x_y = 0, y_x = 0;
  2.         int count = len - 1;        while (count >= 0) {            int[] cur = moves[count];            if (cur[1] == dp[1]) x++;            if (cur[0] == dp[0]) y++;            if (cur[0] == cur[1]) x_y++;            if (cur[0] + cur[1] == 2) y_x++;            count -= 2;        }        if (x >= 3 || y >= 3 || x_y >= 3 || y_x >= 3) {            return len % 2 == 0 ? "B"
  3. : "A"
  4. ;        }        if (len < 9) return "Pending";        return "Draw"
  5. ;    }}
复制代码


代码逐行讲解


复杂度分析

时间复杂度


空间复杂度



总结的知识点


整合

  1. class Solution {    public String tictactoe(int[][] moves) {        int len = moves.length;        int[] dp = moves[len - 1];        int x = 0, y = 0, x_y = 0, y_x = 0;
  2.         int count = len - 1;        while (count >= 0) {            int[] cur = moves[count];            if (cur[1] == dp[1]) x++;            if (cur[0] == dp[0]) y++;            if (cur[0] == cur[1]) x_y++;            if (cur[0] + cur[1] == 2) y_x++;            count -= 2;        }        if (x >= 3 || y >= 3 || x_y >= 3 || y_x >= 3) {            return len % 2 == 0 ? "B"
  3. : "A"
  4. ;        }        if (len < 9) return "Pending";        return "Draw"
  5. ;    }}
复制代码

总结

通过遍历和统计,能够高效地判断井字棋游戏的胜负环境。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 qidao123.com技术社区-IT企服评测·应用市场 (https://dis.qidao123.com/) Powered by Discuz! X3.4