Skip to content

Commit d02b194

Browse files
authored
Create 1275-find-winner-on-a-tic-tac-toe-game.js
1 parent 8cc7f5a commit d02b194

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* @param {number[][]} moves
3+
* @return {string}
4+
*/
5+
const tictactoe = function(moves) {
6+
const grid = Array.from({ length: 3 }, () => Array(3).fill(''))
7+
for(let i = 0, n = moves.length; i < n; i++) {
8+
const ch = i % 2 === 0 ? 'X' : 'O'
9+
const [r, c] = moves[i]
10+
grid[r][c] = ch
11+
const res = chk(ch, grid)
12+
if(res) return ch === 'X' ? 'A' : 'B'
13+
}
14+
15+
return moves.length < 9 ? 'Pending' : 'Draw'
16+
};
17+
18+
function chk(ch, grid) {
19+
for(let i = 0; i < 3; i++) {
20+
if(
21+
grid[i][0] === ch &&
22+
grid[i][1] === ch &&
23+
grid[i][2] === ch
24+
) return true
25+
}
26+
27+
for(let i = 0; i < 3; i++) {
28+
if(
29+
grid[0][i] === ch &&
30+
grid[1][i] === ch &&
31+
grid[2][i] === ch
32+
) return true
33+
}
34+
35+
36+
if(
37+
grid[0][0] === ch &&
38+
grid[1][1] === ch &&
39+
grid[2][2] === ch
40+
) return true
41+
42+
if(
43+
grid[0][2] === ch &&
44+
grid[1][1] === ch &&
45+
grid[2][0] === ch
46+
) return true
47+
48+
return false
49+
}

0 commit comments

Comments
 (0)