机试真题 五子棋判定问题

两种主流思想:

1.直接全部扫描棋盘,按四个方向逐个遍历,不仅麻烦而且很傻;

2.每落一个子,直接对该子进行四个方向判定,且判定的时可以一个方向左右加和;

#include<iostream>
#include<vector>
#include<string>
using namespace std;

const int maxn = 13;
int ma[maxn][maxn];

void printma() {
    for (int i = 0; i < maxn; i++) {
        for (int j = 0; j < maxn; j++) {
            if (ma[i][j] == 1) {
                cout << "o";
            }
            else if (ma[i][j] == -1) {
                cout << "x";
            }
            else {
                cout << "#";
            }
            cout << " ";
        }
        cout << endl;
    }
}

int henc(int x, int y) {
    int cnt = 0;
    for (int i = x; i < maxn&&ma[x][y]==ma[i][y]; i++) {
        cnt++;
    }
    for (int i = x - 1; i >= 0 && ma[x][y] == ma[i][y]; i--)
        cnt++;
    return cnt;
}

int shuc(int x, int y) {
    int cnt = 0;
    for (int i = y; i < maxn&&ma[x][y] == ma[x][i]; i++) {
        cnt++;
    }
    for (int i = y - 1; i >= 0 && ma[x][y] == ma[x][i]; i--)
        cnt++;
    return cnt;
}

int xzc(int x, int y) {
    int cnt = 0;
    for (int i = x, j = y; i < maxn&&y < maxn&&ma[x][y] == ma[i][j]; i++, j++) {
        cnt++;
    }
    for (int i = x-1, j = y-1; i >=0&&y >= 0&&ma[x][y] == ma[i][j]; i--, j--) {
        cnt++;
    }
    return cnt;
}

int xyc(int x, int y) {
    int cnt = 0;
    for (int i = x, j = y; i >=0&&y < maxn&&ma[x][y] == ma[i][j]; i--, j++) {
        cnt++;
    }
    for (int i = x, j = y; i < maxn && y >= 0 &&ma[x][y] == ma[i][j]; i++, j--) {
        cnt++;
    }
    return cnt;
}

bool charge(int x,int y) {
    if (henc(x, y) == 5 || shuc(x, y) == 5 || xzc(x, y) == 5 || xyc(x, y) == 5)
        return true;
    else
        return false;
}

int main() {
    int x, y;
    int f = 1;
    while (1) {
        cin >> x >> y;
        ma[x][y] = f;
        printma();
        if (charge(x, y)) {
            if (f == 1) {
                cout << "黑o胜利" << endl;
            }
            else {
                cout << "白x胜利" << endl;
            }
            break;
        }
        f = -f;
    }
    return 1;
}

猜你喜欢

转载自www.cnblogs.com/songlinxuan/p/12688294.html