Q5:小红的四子棋
第五题大意:五子棋的简略版四子棋,给定一个棋盘,判断是否有棋子连成4个及以上
思路:模拟/穷举所有的可能(行,列,主副对角线)
注意所谓主对角线和副对角线遍历时的坐标变化
一、图解如下
二、代码实现:
#include <bits/stdc++.h>
using namespace std;typedef long long ll;
const int N = 1007; // 定义最大范围
char g[N][N];
int cnt = 0;
//.rr..
//p.p..
//.prp.
//ppprr
//....r
//四子棋判断
bool check(int x, int y) //(x,y)
{//行cnt = 0;for (int j = y- 3; j <= y + 3; j++){if (j < 1 || j>N ) //越界判断{continue;}if (g[x][j] !=g[x][y]) cnt = 0;if (g[x][j] == g[x][y]) //相等cnt++{cnt++;if (cnt == 4) return true;}}//列cnt = 0;for (int i = x - 3; i <= x + 3; i++){if (i < 1 || i>N) //越界判断{continue;}if (g[i][y] !=g[x][y]) cnt = 0;if (g[i][y] == g[x][y]) //相等cnt++{cnt++;if (cnt == 4) return true;}}// 从左下到右上 /cnt = 0;for (int i = x - 3,j = y + 3; i <= x + 3 && j >= y-3; i++,j--){if (i < 1 || i>N || j<1 || j>N) //越界判断{continue;}if (g[i][j]!=g[x][y]) cnt = 0;if (g[i][j] == g[x][y]) //相等cnt++{cnt++;if (cnt == 4) return true;}}// 从左上到右下 \
cnt = 0;for (int i = x - 3, j = y - 3; i <= x + 3 && j <=y + 3; i++, j++){if (i < 1 || i>N || j<1 || j>N ) //越界判断{continue;}if (g[i][j] != g[x][y]) cnt = 0;if (g[i][j] == g[x][y]) //相等cnt++{cnt++;if (cnt == 4) return true;}}return false;
}void solve()
{int n = 5, m = 5;for (int i = 1; i <= n; i++){for (int j = 1; j <= m; j++){cin >> g[i][j];}}// 遍历每个棋子,检查是否有四连子for (int i = 1; i <= n; i++) {for (int j = 1; j <= m; j++) {if (g[i][j] == 'r') { // 当前节点是小红if (check(i, j)) {cout << "小红" << '\n';return;}}if (g[i][j] == 'p') // 当前节点是小紫{if (check(i, j)) {cout << "小紫" << '\n';return;}}}}cout << "continue" << '\n'; // 没有胜利者
}int main() {ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);int t = 1; //cin >> t;while (t--) solve();system("pause");return 0;
}