给定一个二维数组board,代表棋盘,其中元素为1的代表是当前玩家的棋子,0表示没有棋子,-1代表是对方玩家的棋子。当一方棋子在横竖斜方向上有连成排的及获胜(及井字棋规则),返回当前玩家是否胜出。
测试样例:
[[1,0,1],[1,-1,-1],[1,-1,0]]
返回:true
import java.util.*; public class Board { public boolean checkWon(int[][] board) { int sum; int n = board.length; //检查行的元素和 for (int i = 0; i < n; i++) { sum = 0; for (int j = 0; j < n; j++) { sum += board[i][j]; } if(sum == n) { return true; } } //检查列的元素和 for (int i = 0; i < n; i++) { sum = 0; for (int j = 0; j < n; j++) { sum += board[j][i]; } if(sum == n) { return true; } } sum = 0; for (int i = 0; i < n; i++) { sum += board[i][i]; } if(sum == n) { return true; } sum = 0; for (int i = 0; i < n; i++) { sum += board[i][n-1-i]; } if(sum == n) { return true; } return false; } }
import java.util.*; public class Board { public boolean checkWon(int[][] board) { int n = board.length; int sum = 0; int i = 0; int j = 0; for( i = 0;i < n;i++){ sum = 0; for( j = 0;j < n;j++){ //每行元素相加 i 先不变,j++ sum += board[i][j]; } if(sum == n){ return true; } } for( i = 0;i < n;i++){ sum = 0; for( j = 0;j < n;j++){ //每行元素相加 j 先不变,i++ sum += board[j][i]; } if(sum == n){ return true; } } //判断主对角线元素 主对角线;两个下标元素相等 sum = 0; for( i = 0;i < n;i++){ sum += board[i][i]; } if(sum == n){ return true; } //副对角线两个下标值相加为n - 1 sum = 0; for( i = 0;i < n;i++){ sum += board[i][n - 1 - i]; } if(sum == n){ return true; } return false; } }
public boolean checkWon(int[][] board) { return board[0][0] + board[0][1] + board[0][2] == 3 || board[1][0] + board[1][1] + board[1][2] == 3 || board[2][0] + board[2][1] + board[2][2] == 3 || board[0][0] + board[1][0] + board[2][0] == 3 || board[0][1] + board[1][1] + board[2][1] == 3 || board[0][2] + board[1][2] + board[2][2] == 3 || board[0][0] + board[1][1] + board[2][2] == 3 || board[0][2] + board[1][1] + board[2][0] == 3; }
import java.util.*;