Tic-tac-toe

这道题就是模拟题,做起来主要是细心

总结点

还是得知道写函数,千万千万别分类讨论然后写成一坨,这种是改都没法改的垃圾代码.

模拟题如果复杂点就写函数,实现各个功能,如果简单点就直接暴力枚举对着思路实现就行

写函数,写函数,写函数,重要的事情说三遍,一定要写函数,一定要写函数,一定要写函数!!!!

复制代码
#include<bits/stdc++.h>
#include<unordered_set>
#include<unordered_map>
#define endl '\n'
#define int int64_t
using namespace std;
char ch[4][4];
int x = 0, o = 0, dot = 0;
bool Awin() {
    if (ch[1][1] == 'X' && ch[2][2] == 'X' && ch[3][3] == 'X') return true;
    if (ch[3][1] == 'X' && ch[2][2] == 'X' && ch[1][3] == 'X') return true;
    for (int i = 1; i <= 3; ++i) {
        for (int j = 1; j <= 3; ++j) {
            if (ch[i][j] == 'X') {
                if (ch[i][1] == 'X' && ch[i][2] == 'X' && ch[i][3] == 'X') return true;//横着赢
                if (ch[1][j] == 'X' && ch[2][j] == 'X' && ch[3][j] == 'X') return true;//竖着赢
            }
        }
    }
    return false;
}
bool Bwin() {
    if (ch[1][1] == '0' && ch[2][2] == '0' && ch[3][3] == '0') return true;
    if (ch[3][1] == '0' && ch[2][2] == '0' && ch[1][3] == '0') return true;
    for (int i = 1; i <= 3; ++i) {
        for (int j = 1; j <= 3; ++j) {
            if (ch[i][j] == '0') {
                if (ch[i][1] == '0' && ch[i][2] == '0' && ch[i][3] == '0') return true;//横着赢
                if (ch[1][j] == '0' && ch[2][j] == '0' && ch[3][j] == '0') return true;//竖着赢
            }
        }
    }
    return false;
}
bool isValid() {
      // 棋子个数    是不是赢了之后又下了
    if (Awin() && Bwin()) return false;
    if (Awin()) return x == o + 1;
    if (Bwin()) return x == o;
    return x == o + 1 ||  x == o;
}
bool isDraw() {
    if (dot) return false;
    return !Awin() && !Bwin();
}
signed main() {
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    for (int i = 1; i <= 3; ++i)
        for (int j = 1; j <= 3; ++j) {
            cin >> ch[i][j];
            if (ch[i][j] == 'X') x++;
            else if (ch[i][j] == '0') o++;
            else dot++;
        }
    if (!isValid()) cout << "illegal" << endl, exit(0);
    if (Awin()) cout << "the first player won" << endl, exit(0);
    if (Bwin()) cout << "the second player won" << endl, exit(0);
    if (isDraw()) cout << "draw" << endl, exit(0);
    if (x == o) cout << "first" << endl;
    else cout << "second" << endl;
    return 0;
}
相关推荐
菜鸟233号5 分钟前
力扣513 找树左下角的值 java实现
java·数据结构·算法·leetcode
亭上秋和景清7 分钟前
指针进阶:函数指针详解
开发语言·c++·算法
leoufung8 分钟前
LeetCode 22:Generate Parentheses 题解(DFS / 回溯)
算法·leetcode·深度优先
断剑zou天涯1 小时前
【算法笔记】bfprt算法
java·笔记·算法
youngee111 小时前
hot100-47岛屿数量
算法
无限进步_2 小时前
深入理解 C/C++ 内存管理:从内存布局到动态分配
c语言·c++·windows·git·算法·github·visual studio
长安er2 小时前
LeetCode 34排序数组中查找元素的第一个和最后一个位置-二分查找
数据结构·算法·leetcode·二分查找·力扣
点云SLAM3 小时前
C++ 中traits 类模板(type traits / customization traits)设计技术深度详解
c++·算法·c++模板·c++高级应用·traits 类模板·c++17、20·c++元信息
CoderYanger3 小时前
动态规划算法-两个数组的dp(含字符串数组):48.最长重复子数组
java·算法·leetcode·动态规划·1024程序员节
liu****3 小时前
9.二叉树(一)
c语言·开发语言·数据结构·算法·链表