小红的夹吃棋
[题目链接](https://www.nowcoder.com/practice/364c9d2c2af247ddb7df8f71f5f7ca5e)
思路
纯模拟题。在 的棋盘上,判断黑棋和白棋是否被"夹吃"。
夹吃判定
对于棋盘上的每个棋子,检查它是否被对方颜色的棋子夹住:
- 横向夹吃:当前棋子位于某行的中间位置(列号为 1),且左右两侧都是对方棋子。
- 纵向夹吃:当前棋子位于某列的中间位置(行号为 1),且上下两侧都是对方棋子。
只要存在任意一个黑棋被白棋夹住,就认为"黑棋被夹吃";白棋同理。
胜负判定
用两个布尔变量分别记录黑棋是否被夹吃、白棋是否被夹吃:
- 双方都被夹吃,或都没被夹吃:平局,输出
draw。 - 只有白棋被夹吃(黑方夹吃了白方):小红胜,输出
kou。 - 只有黑棋被夹吃(白方夹吃了黑方):小紫胜,输出
yukari。
复杂度分析
- 时间复杂度:
,其中
为测试用例数。每个测试用例遍历
个格子,为常数。
- 空间复杂度:
。
代码
#include <bits/stdc++.h>
using namespace std;
int main(){
int t;
scanf("%d",&t);
while(t--){
char g[3][4];
for(int i=0;i<3;i++) scanf("%s",g[i]);
bool blackCaptured=false, whiteCaptured=false;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(g[i][j]=='*'){
if(j>0 && j<2 && g[i][j-1]=='o' && g[i][j+1]=='o') blackCaptured=true;
if(i>0 && i<2 && g[i-1][j]=='o' && g[i+1][j]=='o') blackCaptured=true;
} else if(g[i][j]=='o'){
if(j>0 && j<2 && g[i][j-1]=='*' && g[i][j+1]=='*') whiteCaptured=true;
if(i>0 && i<2 && g[i-1][j]=='*' && g[i+1][j]=='*') whiteCaptured=true;
}
}
}
if(blackCaptured && whiteCaptured) puts("draw");
else if(whiteCaptured) puts("kou");
else if(blackCaptured) puts("yukari");
else puts("draw");
}
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
char[][] g = new char[3][3];
for (int i = 0; i < 3; i++) {
String s = sc.next();
for (int j = 0; j < 3; j++) g[i][j] = s.charAt(j);
}
boolean blackCaptured = false, whiteCaptured = false;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (g[i][j] == '*') {
if (j > 0 && j < 2 && g[i][j-1] == 'o' && g[i][j+1] == 'o') blackCaptured = true;
if (i > 0 && i < 2 && g[i-1][j] == 'o' && g[i+1][j] == 'o') blackCaptured = true;
} else if (g[i][j] == 'o') {
if (j > 0 && j < 2 && g[i][j-1] == '*' && g[i][j+1] == '*') whiteCaptured = true;
if (i > 0 && i < 2 && g[i-1][j] == '*' && g[i+1][j] == '*') whiteCaptured = true;
}
}
}
if (blackCaptured && whiteCaptured) System.out.println("draw");
else if (whiteCaptured) System.out.println("kou");
else if (blackCaptured) System.out.println("yukari");
else System.out.println("draw");
}
}
}

京公网安备 11010502036488号