Skip to content

Commit c4ddd27

Browse files
author
ChienkuChen
committed
Add 348 version 2
1 parent 696ab51 commit c4ddd27

File tree

2 files changed

+77
-147
lines changed

2 files changed

+77
-147
lines changed

src/_340/TicTacToe.java

Lines changed: 0 additions & 147 deletions
This file was deleted.

src/_348/TicTacToe.java

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package _348;
2+
3+
public class TicTacToe {
4+
private int n;
5+
private int[] rows;
6+
private int[] columns;
7+
private int diagonal;
8+
private int antiDiagonal;
9+
10+
/**
11+
* Initialize your data structure here.
12+
*/
13+
public TicTacToe(int n) {
14+
this.n = n;
15+
rows = new int[n];
16+
columns = new int[n];
17+
}
18+
19+
/**
20+
* Player {player} makes a move at ({row}, {col}).
21+
*
22+
* @param row The row of the board.
23+
* @param col The column of the board.
24+
* @param player The player, can be either 1 or 2.
25+
* @return The current winning condition, can be either:
26+
* 0: No one wins.
27+
* 1: Player 1 wins.
28+
* 2: Player 2 wins.
29+
*/
30+
public int move(int row, int col, int player) {
31+
switch (player) {
32+
case 1:
33+
if (row == col) {
34+
diagonal++;
35+
}
36+
37+
if ((row + col) == n - 1) {
38+
antiDiagonal++;
39+
}
40+
41+
rows[row]++;
42+
columns[col]++;
43+
44+
if (rows[row] == n || columns[col] == n || antiDiagonal == n || diagonal == n)
45+
return 1;
46+
return 0;
47+
case 2:
48+
if (row == col) {
49+
diagonal--;
50+
}
51+
52+
if ((row + col) == n - 1) {
53+
antiDiagonal--;
54+
}
55+
56+
rows[row]--;
57+
columns[col]--;
58+
59+
if (rows[row] == -n || columns[col] == -n || antiDiagonal == -n || diagonal == -n)
60+
return 2;
61+
return 0;
62+
default:
63+
return -1;
64+
}
65+
}
66+
67+
public static void main(String[] args) {
68+
final TicTacToe ticTacToe = new TicTacToe(3);
69+
System.out.println(ticTacToe.move(0, 0, 1));
70+
System.out.println(ticTacToe.move(0, 2, 2));
71+
System.out.println(ticTacToe.move(2, 2, 1));
72+
System.out.println(ticTacToe.move(1, 1, 2));
73+
System.out.println(ticTacToe.move(2, 0, 1));
74+
System.out.println(ticTacToe.move(1, 0, 2));
75+
System.out.println(ticTacToe.move(2, 1, 1));
76+
}
77+
}

0 commit comments

Comments
 (0)