【Leetcode】1275. Find Winner on a Tic Tac Toe Game

题目地址:

https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/

玩Tic Tac Toe游戏,在一个 3 × 3 3\times 3 3×3方格上,先手是 A A A,走'X',后手是 B B B,走'O',给定他们每次走的位置,题目保证每次走的时候都是合法的。问胜者是谁,返回胜者名字。如果游戏还可以继续进行则输出“Pending”,否则输出“Draw”。

代码如下:

class Solution {
 public:
  string tictactoe(vector<vector<int>>& moves) {
    char a[3][3] = {0};
    auto f = [&](int x, int y, char ch) {
      a[x][y] = ch;
      string res = ch == 'X' ? "A" : "B";
      for (int i = 0; i < 3; i++) {
        if (a[i][0] == ch && a[i][1] == ch && a[i][2] == ch) return res;
        if (a[0][i] == ch && a[1][i] == ch && a[2][i] == ch) return res;
        if (a[0][0] == ch && a[1][1] == ch && a[2][2] == ch) return res;
        if (a[0][2] == ch && a[1][1] == ch && a[2][0] == ch) return res;
      }
      return string();
    };
    bool b = true;
    for (auto& move : moves) {
      int x = move[0], y = move[1];
      auto res = f(x, y, b ? 'X' : 'O');
      if (res.size()) return res;
      b = !b;
    }

    return moves.size() < 9 ? "Pending" : "Draw";
  }
};

时空复杂度 O ( 1 ) O(1) O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值