本文主要是介绍Design Tic-Tac-Toe,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
巩固矩阵的操作,尤其是对角线的操作。
之后处理follow up
public class TicTacToe {int[][] matrix;/** Initialize your data structure here. */public TicTacToe(int n) {matrix = new int[n][n];}/** Player {player} makes a move at ({row}, {col}).@param row The row of the board.@param col The column of the board.@param player The player, can be either 1 or 2.@return The current winning condition, can be either:0: No one wins.1: Player 1 wins.2: Player 2 wins. */public int move(int row, int col, int player) {matrix[row][col] = player;int len = matrix.length;for (int i = 0; i < len; i++) {if (matrix[i][0] != 0) {int j = 1;for (; j < len; j++) {if (matrix[i][j] != matrix[i][j - 1]) {break;}}if (j == len) {return matrix[i][0];}}}for (int i = 0; i < len; i++) {if (matrix[0][i] != 0) {int j = 1;for (; j < len; j++) {if (matrix[j][i] != matrix[j - 1][i]) {break;}}if (j == len) {return matrix[0][i];}}}if (matrix[0][0] != 0) {int i = 1, j = 1;for (; i < len && j < len; i++, j++) {if (matrix[i][j] != matrix[i - 1][j - 1]) {break;}}if (i == len) {return matrix[0][0];}}if (matrix[0][len - 1] != 0) {int i = 1, j = len - 2;for (; i < len && j >= 0; i++, j--) {if (matrix[i][j] != matrix[i - 1][j + 1]) {break;}}if (i == len) {return matrix[0][len - 1];}}return 0;}
}/*** Your TicTacToe object will be instantiated and called as such:* TicTacToe obj = new TicTacToe(n);* int param_1 = obj.move(row,col,player);*/
这篇关于Design Tic-Tac-Toe的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!