程序媛詹妮弗
终身学习

Design a Tic-tac-toe game that is played between two players on a n x n grid.

You may assume the following rules:

  1. A move is guaranteed to be valid and is placed on an empty block.
  2. Once a winning condition is reached, no more moves is allowed.
  3. A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game.
Given n = 3, assume that player 1 is "X" and player 2 is "O" in the board.

TicTacToe toe = new TicTacToe(3);

toe.move(0, 0, 1); -> Returns 0 (no one wins)
|X| | |
| | | |    // Player 1 makes a move at (0, 0).
| | | |

toe.move(0, 2, 2); -> Returns 0 (no one wins)
|X| |O|
| | | |    // Player 2 makes a move at (0, 2).
| | | |

toe.move(2, 2, 1); -> Returns 0 (no one wins)
|X| |O|
| | | |    // Player 1 makes a move at (2, 2).
| | |X|

toe.move(1, 1, 2); -> Returns 0 (no one wins)
|X| |O|
| |O| |    // Player 2 makes a move at (1, 1).
| | |X|

toe.move(2, 0, 1); -> Returns 0 (no one wins)
|X| |O|
| |O| |    // Player 1 makes a move at (2, 0).
|X| |X|

toe.move(1, 0, 2); -> Returns 0 (no one wins)
|X| |O|
|O|O| |    // Player 2 makes a move at (1, 0).
|X| |X|

toe.move(2, 1, 1); -> Returns 1 (player 1 wins)
|X| |O|
|O|O| |    // Player 1 makes a move at (2, 1).
|X|X|X|

 

思路:

player1 走一步加1

player2 走一步减1

看谁sum的绝对值能先到达3, 谁赢

 

code

 1 class TicTacToe {
 2     private int[] rows;
 3         private int[] cols;
 4         private int diagonal;
 5         private int antiDiagonal;
 6 
 7     /** Initialize your data structure here. */
 8     public TicTacToe(int n) {
 9         rows = new int[n];
10         cols = new int[n];
11     }
12 
13     /** Player {player} makes a move at ({row}, {col}).
14         @param row The row of the board.
15         @param col The column of the board.
16         @param player The player, can be either 1 or 2.
17         @return The current winning condition, can be either:
18                 0: No one wins.
19                 1: Player 1 wins.
20                 2: Player 2 wins. */
21     public int move(int row, int col, int player) {
22         int toAdd = player == 1 ? 1 : -1;
23 
24         rows[row] += toAdd;
25         cols[col] += toAdd;
26         if (row == col)
27         {
28             diagonal += toAdd;
29         }
30 
31         if (col == (cols.length - row - 1))
32         {
33             antiDiagonal += toAdd;
34         }
35 
36         int size = rows.length;
37         if (Math.abs(rows[row]) == size ||
38             Math.abs(cols[col]) == size ||
39             Math.abs(diagonal) == size  ||
40             Math.abs(antiDiagonal) == size)
41         {
42             return player;
43         }
44 
45         return 0;  // No one wins.
46     }
47 }

 

posted on 2019-07-31 06:33  程序媛詹妮弗  阅读(258)  评论(0编辑  收藏  举报