-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0348_design_tic_tac_toe.html
More file actions
232 lines (199 loc) Β· 10.8 KB
/
0348_design_tic_tac_toe.html
File metadata and controls
232 lines (199 loc) Β· 10.8 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 348: Design Tic-Tac-Toe - Algorithm Visualization</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#348</span> Design Tic-Tac-Toe</h1>
<p>Design a Tic-Tac-Toe game that can check if a player wins after each move in O(1) time.</p>
<div class="problem-meta">
<span class="meta-tag">π§ Design</span>
<span class="meta-tag">π Array</span>
<span class="meta-tag">β±οΈ O(1) per move</span>
<span class="meta-tag">πΎ O(n)</span>
</div>
<div class="file-ref">
π Python: <code>python/0348_design_tic_tac_toe/0348_design_tic_tac_toe.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>π§ How It Works (Layman's Terms)</h4>
<p>Track <strong>counts</strong> instead of checking entire board:</p>
<ul>
<li><strong>Row counts:</strong> +1 for player 1, -1 for player 2</li>
<li><strong>Column counts:</strong> Same idea for each column</li>
<li><strong>Diagonals:</strong> Two extra counters for diagonals</li>
<li><strong>Win condition:</strong> If any count = n or -n β winner!</li>
</ul>
</div>
<div class="visualization-section">
<h3>π¬ Step-by-Step Visualization</h3>
<div class="controls">
<label>Board size n = </label>
<select id="boardSize" onchange="reset()" style="padding: 8px; border-radius: 5px;">
<option value="3" selected>3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<button class="btn btn-warning" onclick="reset()">New Game</button>
</div>
<div class="status-message" id="statusMessage">
Player 1 (X) turn - Click a cell to play
</div>
<div style="display: flex; gap: 30px; flex-wrap: wrap; margin-top: 20px;">
<div style="flex: 1; min-width: 250px;">
<div id="boardDisplay" style="display: grid; gap: 5px; background: #333; padding: 5px; border-radius: 12px; width: fit-content;"></div>
</div>
<div style="flex: 1; min-width: 250px;">
<h4>π Row Counts</h4>
<div id="rowCounts" style="display: flex; gap: 10px; padding: 10px; background: #e3f2fd; border-radius: 8px; flex-wrap: wrap;"></div>
<h4 style="margin-top: 15px;">π Column Counts</h4>
<div id="colCounts" style="display: flex; gap: 10px; padding: 10px; background: #fff3e0; border-radius: 8px; flex-wrap: wrap;"></div>
<h4 style="margin-top: 15px;">π Diagonal Counts</h4>
<div id="diagCounts" style="display: flex; gap: 15px; padding: 10px; background: #f3e5f5; border-radius: 8px;"></div>
<div style="margin-top: 20px; padding: 15px; background: #f5f5f5; border-radius: 12px;">
<h4 style="margin-bottom: 10px;">π Explanation</h4>
<p style="font-size: 0.9em; color: #666;">
Player 1 (X) adds <strong>+1</strong> to counts<br>
Player 2 (O) adds <strong>-1</strong> to counts<br>
Win when any count = <strong>Β±n</strong>
</p>
</div>
</div>
</div>
</div>
<div class="code-section">
<h3>π» Python Solution</h3>
<div class="code-block">
<pre><span class="keyword">class</span> <span class="function">TicTacToe</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(self, n):
self.n = n
self.rows = [<span class="number">0</span>] * n <span class="comment"># Row counts</span>
self.cols = [<span class="number">0</span>] * n <span class="comment"># Column counts</span>
self.diag = <span class="number">0</span> <span class="comment"># Main diagonal</span>
self.anti_diag = <span class="number">0</span> <span class="comment"># Anti-diagonal</span>
<span class="keyword">def</span> <span class="function">move</span>(self, row, col, player):
add = <span class="number">1</span> <span class="keyword">if</span> player == <span class="number">1</span> <span class="keyword">else</span> <span class="number">-1</span>
self.rows[row] += add
self.cols[col] += add
<span class="keyword">if</span> row == col:
self.diag += add
<span class="keyword">if</span> row + col == self.n - <span class="number">1</span>:
self.anti_diag += add
<span class="comment"># Check for win</span>
<span class="keyword">if</span> <span class="function">abs</span>(self.rows[row]) == self.n <span class="keyword">or</span> \
<span class="function">abs</span>(self.cols[col]) == self.n <span class="keyword">or</span> \
<span class="function">abs</span>(self.diag) == self.n <span class="keyword">or</span> \
<span class="function">abs</span>(self.anti_diag) == self.n:
<span class="keyword">return</span> player
<span class="keyword">return</span> <span class="number">0</span></pre>
</div>
</div>
</div>
<script>
let n = 3;
let board = [];
let rows = [];
let cols = [];
let diag = 0;
let antiDiag = 0;
let currentPlayer = 1;
let winner = 0;
let moveCount = 0;
function render() {
// Render board
const boardContainer = document.getElementById('boardDisplay');
boardContainer.style.gridTemplateColumns = `repeat(${n}, 60px)`;
let boardHtml = '';
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
const cell = board[i][j];
let content = '';
let bg = 'white';
if (cell === 1) {
content = 'X';
bg = '#e3f2fd';
} else if (cell === 2) {
content = 'O';
bg = '#ffebee';
}
const clickable = winner === 0 && cell === 0;
boardHtml += `<div onclick="${clickable ? `makeMove(${i}, ${j})` : ''}" style="
width: 60px; height: 60px;
background: ${bg};
display: flex; align-items: center; justify-content: center;
font-size: 2em; font-weight: bold;
color: ${cell === 1 ? '#2196f3' : '#f44336'};
cursor: ${clickable ? 'pointer' : 'default'};
border-radius: 8px;
transition: all 0.2s;
">${content}</div>`;
}
}
boardContainer.innerHTML = boardHtml;
// Render row counts
document.getElementById('rowCounts').innerHTML = rows.map((r, i) =>
`<div style="padding: 8px 12px; background: ${Math.abs(r) === n ? '#4caf50' : 'white'}; color: ${Math.abs(r) === n ? 'white' : 'black'}; border-radius: 6px;">R${i}: ${r}</div>`
).join('');
// Render column counts
document.getElementById('colCounts').innerHTML = cols.map((c, i) =>
`<div style="padding: 8px 12px; background: ${Math.abs(c) === n ? '#4caf50' : 'white'}; color: ${Math.abs(c) === n ? 'white' : 'black'}; border-radius: 6px;">C${i}: ${c}</div>`
).join('');
// Render diagonal counts
document.getElementById('diagCounts').innerHTML = `
<div style="padding: 8px 12px; background: ${Math.abs(diag) === n ? '#4caf50' : 'white'}; color: ${Math.abs(diag) === n ? 'white' : 'black'}; border-radius: 6px;">β Main: ${diag}</div>
<div style="padding: 8px 12px; background: ${Math.abs(antiDiag) === n ? '#4caf50' : 'white'}; color: ${Math.abs(antiDiag) === n ? 'white' : 'black'}; border-radius: 6px;">β Anti: ${antiDiag}</div>
`;
}
function makeMove(row, col) {
if (winner !== 0 || board[row][col] !== 0) return;
const add = currentPlayer === 1 ? 1 : -1;
board[row][col] = currentPlayer;
rows[row] += add;
cols[col] += add;
if (row === col) diag += add;
if (row + col === n - 1) antiDiag += add;
moveCount++;
// Check for win
if (Math.abs(rows[row]) === n ||
Math.abs(cols[col]) === n ||
Math.abs(diag) === n ||
Math.abs(antiDiag) === n) {
winner = currentPlayer;
document.getElementById('statusMessage').textContent =
`π Player ${winner} (${winner === 1 ? 'X' : 'O'}) wins!`;
document.getElementById('statusMessage').style.color = winner === 1 ? '#2196f3' : '#f44336';
} else if (moveCount === n * n) {
document.getElementById('statusMessage').textContent = "π€ It's a draw!";
} else {
currentPlayer = currentPlayer === 1 ? 2 : 1;
document.getElementById('statusMessage').textContent =
`Player ${currentPlayer} (${currentPlayer === 1 ? 'X' : 'O'}) turn - Click a cell to play`;
document.getElementById('statusMessage').style.color = '#333';
}
render();
}
function reset() {
n = parseInt(document.getElementById('boardSize').value);
board = Array.from({ length: n }, () => Array(n).fill(0));
rows = Array(n).fill(0);
cols = Array(n).fill(0);
diag = 0;
antiDiag = 0;
currentPlayer = 1;
winner = 0;
moveCount = 0;
document.getElementById('statusMessage').textContent = 'Player 1 (X) turn - Click a cell to play';
document.getElementById('statusMessage').style.color = '#333';
render();
}
reset();
</script>
</body>
</html>