程式設計入門—Java語言 第五周編程題 2井字棋(5分)

來源:互聯網
上載者:User

標籤:題目   情況   system.in   限制   判斷   import   視頻   存在   輸出   

2

井字棋(5分)

題目內容:

嗯,就是視頻裡說的那個井字棋。視頻裡說了它的基本思路,現在,需要你把它全部實現出來啦。

你的程式先要讀入一個整數n,範圍是[3,100],這表示井字棋棋盤的邊長。比如n=3就表示是一個3x3的棋盤。然後,要讀入n行,每行n個數字,每個數字是1或0,依次表示[0,0]到[n-1,n-1]位置上的棋子。1表示X,0表示O(大寫字母O)。

你的程式要判斷其中是否存在某一方獲勝,獲勝的條件是存在整行或整列或整條對角線或整條反對角線上是相同的棋子。如果存在,則輸出代表獲勝一方字母:X或O(大寫字母X或O);如果沒有任何一方獲勝,則輸出NIL(三個大寫字母,中間是字母I(India的I)。

注意:所給的棋盤上的棋子分布可能出現同一個棋子有多處滿足獲勝的條件,但是不會出現兩種棋子都獲勝的情況。

 

輸入格式:

一個代表棋盤大小的數字n,後面跟上nxn個0或1的數字。

 

輸出格式:

三種輸出之一:

  1. X
  2. O
  3. NIL

均為大寫字母。

 

輸入範例:

  1. 4
  2. 1 0 0 1
  3. 0 1 0 0
  4. 0 0 1 0
  5. 1 0 0 1

 

輸出範例:

  1. X

時間限制:500ms記憶體限制:32000kb

import java.util.Scanner; public class hello{public static void main(String[] args) {// TODO Auto-generated method stubScanner in=new Scanner(System.in);int n=in.nextInt(); //範圍是[3,100]int[][] board= new int[n][n];boolean gotResult=false;int numOfX=0;int numOf0=0;//讀入矩陳陣for(int i=0;i<board.length;i++){for(int j=0;j<board[i].length;j++){board[i][j]=in.nextInt();}}//判斷行for(int i=0;i<board.length;i++){for(int j=0;j<board[i].length;j++){if(board[i][j]==1){numOfX++;}else{numOf0++;}}if(numOfX==n||numOf0==n){gotResult=true;break;}else{numOfX=0;numOf0=0;}}//判斷列if(!gotResult){for(int j=0;j<n;j++){for(int i=0;i<n;i++){if(board[i][j]==1){numOfX++;}else{numOf0++;}}if(numOfX==n||numOf0==n){gotResult=true;break;}else{numOfX=0;numOf0=0;}}}//判斷對角線if(!gotResult){for(int i=0;i<n;i++){if(board[i][i]==1){numOfX++;}else{numOf0++;}}if(numOfX==n||numOf0==n){gotResult=true;}else{numOfX=0;numOf0=0;}}//判斷反對角線if(!gotResult){for(int i=0;i<n;i++){if(board[i][n-i-1]==1){numOfX++;}else{numOf0++;}}if(numOfX==n||numOf0==n){gotResult=true;}else{numOfX=0;numOf0=0;}}//輸出結果if(gotResult){if(numOfX==n){System.out.println("X");}else if(numOf0==n){System.out.println("0");}}else {System.out.println("NIL");}}}

  

程式設計入門—Java語言 第五周編程題 2井字棋(5分)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.