井字棋判断输赢功能实现

xiaoxiao2021-03-01  45

这是原问题:

You will be given the sequence of moves (supposing the first move is always done by X) - by the numbers of cells where marks are placed - and your task is to determine, at which step the first line was completed (by any side).

Input data contain the number of test-cases in the first line. Next lines have one test-case each - exactly 9 numbers, describing cells to which moves are performed in order.Answer should contain the number of the move at which game is won by one of players (starting from 1) or 0 if the game is drawn (no winner) after the last move.

Example:

input data: 3 7 5 4 1 9 2 8 3 6 5 1 3 7 6 4 2 9 8 5 1 2 8 6 4 7 3 9 answer: 7 6 0

Test data: copy and paste them as an input for your program

11 8 4 1 3 7 6 9 5 2 8 6 5 7 3 1 4 2 9 9 8 7 6 5 1 4 2 3 4 5 6 8 2 1 7 9 3 9 6 8 2 5 7 3 4 1 6 8 4 3 5 2 9 1 7 1 3 4 6 7 5 9 2 8 3 8 2 4 1 7 9 5 6 5 9 7 1 6 2 4 8 3 7 2 6 5 4 8 9 1 3 9 3 5 1 6 7 8 4 2

 

test data 直接全部复制然后粘贴即可。

思路:两个二维数组分别存储x与o的棋子的落点,提供以数组为形参的方法判断是否获胜。

我的要求是,就算下棋没下完也得判断出来输赢。

最后需要释放未输入完的数据。

以下是代码:

import java.util.Scanner; public class test { public boolean flag(int[][] x){ int e = 0;//e作为是否连线的标志,若是,则e应该等于3 for(int i=0;i<3;i++) {//从行判断输赢 for (int j = 0; j < 3; j++) { if (x[i][j] == 1) e++; } if (e == 3) return true; e = 0; } for(int i=0;i<3;i++){//从列判断输赢 for(int j=0;j<3;j++){ if(x[j][i]==1) e++; } if(e==3) return true; e = 0; } for(int i=0;i<3;i++){//斜线判断输赢 if(x[i][i]==1) e++; } if(e==3) return true; e = 0; for(int i=0;i<3;i++){//反斜线判断输赢 if(x[i][2-i]==1) e++; } if(e==3) return true; return false; } public void change(int[][] x,int xnum){//实现妻子落点定位的方法 switch (xnum){ case 1:x[0][0]=1;break; case 2:x[0][1]=1;break; case 3:x[0][2]=1;break; case 4:x[1][0]=1;break; case 5:x[1][1]=1;break; case 6:x[1][2]=1;break; case 7:x[2][0]=1;break; case 8:x[2][1]=1;break; case 9:x[2][2]=1;break; } } public static void main(String[] args) { test t=new test(); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for(int i=0;i<n;i++){ int xx=0; int yy=0; int[][] x=new int[3][3]; int[][] y=new int[3][3]; while(true) {//当输赢分出来以后才会退出循环 int xnum = sc.nextInt(); t.change(x, xnum); xx++; boolean xflag = t.flag(x); if(xflag){ System.out.print((xx+yy)+" "); break; } if(xx+yy==9){//如果下了9步,则输出0表示和棋 System.out.println(0+" "); break; } int ynum = sc.nextInt(); t.change(y,ynum); yy++; boolean yflag = t.flag(y); if(yflag){ System.out.println((xx+yy)+" "); break; } } if(xx+yy!=9)//此处释放未输出的数字 while(true){ if(xx+yy!=9){ sc.nextInt(); xx++; } else break; } } } }

 输出结果:

7 0 9 8 9 5 5 5 7 6 8

转载请注明原文地址: https://www.6miu.com/read-3450089.html

最新回复(0)