c++ 井字棋英文名叫 Tic-Tac-Toe是一种在 33 格子上进行的连珠游戏和五子棋类似由于棋盘一般不画边框格线排成井字故得名。游戏需要的工具仅为纸和笔然后由分别代表 O 和 X 的两个游戏者轮流在格子里留下标记一般来说先手者为 X任意三个标记形成一条直线则为获胜。来自百度百科请你判断后手者是否存在任意三个标记形成一条直线?输入格式23第一行输入一个整数 t1=t=1000代表 t 组输入。
Here is a possible solution in C++:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool checkLine(const vector<string>& board, int r, int c, int dr, int dc) {
char symbol = board[r][c];
for (int i = 0; i < 3; i++) {
if (board[r][c] != symbol) {
return false;
}
r += dr;
c += dc;
}
return true;
}
bool checkWin(const vector<string>& board) {
// Check rows
for (int r = 0; r < 3; r++) {
if (checkLine(board, r, 0, 0, 1)) {
return true;
}
}
// Check columns
for (int c = 0; c < 3; c++) {
if (checkLine(board, 0, c, 1, 0)) {
return true;
}
}
// Check diagonals
if (checkLine(board, 0, 0, 1, 1) || checkLine(board, 0, 2, 1, -1)) {
return true;
}
return false;
}
int main() {
int t;
cin >> t;
while (t--) {
vector<string> board(3);
for (int i = 0; i < 3; i++) {
cin >> board[i];
}
bool hasWin = checkWin(board);
if (hasWin) {
cout << "yes" << endl;
} else {
cout << "no" << endl;
}
}
return 0;
}
Explanation:
- The
checkLinefunction checks if there are three consecutive symbols in a row, column, or diagonal starting from a given position. - The
checkWinfunction checks if any of the rows, columns, or diagonals have three consecutive symbols of the same player. - In the main function, we read the number of test cases
t. For each test case, we read the game board and check if the second player (O) has won. We output "yes" if they have won, and "no" otherwise
原文地址: https://www.cveoy.top/t/topic/hUE9 著作权归作者所有。请勿转载和采集!