题目描述
对于一个给定的井字棋棋盘,请设计一个高效算法判断当前玩家是否获胜。
给定一个二维数组board,代表当前棋盘,其中元素为1的代表是当前玩家的棋子,为0表示没有棋子,为-1代表是对方玩家的棋子。
测试样例:
[[1,0,1],[1,-1,-1],[1,-1,0]]
返回:
true
class Board {
public:
bool checkWon(vector<vector<int> > board) {
// write code here
int rows = board.size();
int cols = board[0].size();
int i = 0, j = 0;
for(i = 0; i < rows; i++){
if((board[i][0] == board[i][1]) &&
(board[i][0] == board[i][2]) &&
(board[i][0] == 1)){
return true;
}
}
for(j = 0; j < cols; j++){
if((board[0][j] == board[1][j]) &&
(board[0][j] == board[2][j]) &&
(board[0][j] == 1)){
return true;
}
}
if(board[0][0] == board[1][1] &&
board[0][0] == board[2][2] &&
board[0][0] == 1){
return true;
}
if(board[2][0] == board[1][1] &&
board[2][0] == board[0][2] &&
board[2][0] == 1){
return true;
}
return false;
}
};
比较简单的简答方法:
bool checkWon(vector<vector<int> > a) {
if(a[0][0]+a[1][1]+a[2][2]==3) return true;
if(a[0][2]+a[1][1]+a[2][0]==3) return true;
for(int i=0;i<3;i++){
if(a[i][0]+a[i][1]+a[i][2]==3) return true;
if(a[0][i]+a[1][i]+a[2][i]==3) return true;
}
return false;
}