二维数组(判断井字棋的输赢)

#include

int main() { //定义棋盘 const int size = 3; int qipan[][3] = { {1,1,1}, {1,0,0}, {1,0,1}, };

int result = -1; //初始结果为平局

//这是有两重循环的代码,下方有无循环的代码
//第一次循环:当行相同时,列上是否已经出现三个1或者三个0
//第二重循环:当列相同时,行上是否已经出现了三个1或者三个0
int hang,lie;
int number0,number1;
int count = 2;//确定循环次数
while (count) {
    for (hang = 0;hang<size;hang++) {
        number0 = 0;
        number1 = 0;
        for (lie = 0;lie < size; lie ++) {
            if (qipan[hang][lie] == 1) {
                number1++;
            } else {
                number0++;
            }
        }
        if (number1 == size) {
            result = 1;
        } else if (number0 == size) {
            result = 0;
        }
        if (result == 1 || result == 0) {
        goto out;
        }
    }
    int substitute = hang;//hang与lie的替换,实现下方,列相同,行的检测
    hang = lie;
    lie = substitute;
    count--;

}
/*(没有循环下,行列分开的,这是列相同,行的检测)
//当列相同时,行上是否已经出现了三个1或者三个0
for (lie = 0; lie< size; lie++) {
    number1 = 0;
    number0 = 0;
    for (hang = 0;hang<size;hang++) {
        if (qipan[hang][lie] == 1) {
            number1++;
        } else {
            number0++;
        }
    }
    if (number1 == size) {
        result = 1;
        break;
    } else if (number0 == size) {
        result = 0;
        break;
    }
}
if (result == 1 || result == 0) {
    goto out;
}
*/


//printf("zhengchang");
//检查正斜线
number1 = 0,number0 = 0;
for (hang = 0;hang<size;hang++) {
    if (qipan[hang][hang] == 1) {
        number1++;
    } else {
        number0++;
    }
}
if (number1 == size) {
    result = 1;
} else if (number0 == size) {
    result = 0;
}
if (result == 1 || result == 0) {
    goto out;
}

//printf("zhengchang");
//检查反斜线
number1 = 0,number0 = 0;
for (hang = 0;hang<size;hang++) {
    if (qipan[hang][size-1-hang] == 1) {
        number1++;
    } else {
        number0++;
    }
}
if (number1 == size) {
    result = 1;
} else if (number0 == size) {
    result = 0;
}

out: switch(result) { case -1:printf("平局");break; case 0:printf("写0的一方获胜");break; default:printf("写1的一方获胜");break; }

return 0;

}

JSRUN前端笔记, 是针对前端工程师开放的一个笔记分享平台,是前端工程师记录重点、分享经验的一个笔记本。JSRUN前端采用的 MarkDown 语法 (极客专用语法), 这里属于IT工程师。