-
Notifications
You must be signed in to change notification settings - Fork 42
/
solution.js
63 lines (61 loc) · 1.53 KB
/
solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* @param {string[]} board
* @return {string}
*/
var tictactoe = function (board) {
const N = board.length;
if (N === 1) {
if (board[0][0] === ' ') {
return 'Pending';
} else {
return 'O';
}
}
const colMatch = new Array(N).fill(true);
let hasRest = false;
for (let i = 0; i < N; i++) {
let rowMatch = true;
for (let j = 0; j < N; j++) {
if (board[i][j] === ' ') {
hasRest = true;
colMatch[j] = false;
rowMatch = false;
continue;
}
if (j > 0 && rowMatch && board[i][j] !== board[i][0]) {
rowMatch = false;
}
if (i > 0 && colMatch[j] && board[i][j] !== board[0][j]) {
colMatch[j] = false;
}
}
if (rowMatch) {
return board[i][0];
}
}
for (let j = 0; j < N; j++) {
if (colMatch[j]) {
return board[0][j];
}
}
let diagonal1 = board[0][0] !== ' ';
let diagonal2 = board[0][N - 1] !== ' ';
for (let i = 1; i < N; i++) {
if (diagonal1 && board[i][i] !== board[0][0]) {
diagonal1 = false;
}
if (diagonal2 && board[i][N - i - 1] !== board[0][N - 1]) {
diagonal2 = false;
}
}
if (diagonal1) {
return board[0][0];
}
if (diagonal2) {
return board[0][N - 1];
}
if (hasRest) {
return 'Pending';
}
return 'Draw';
};