Skip to content

Commit 2aa02b1

Browse files
committed
Added 1 JS solution for problem 130
1 parent 5fba15a commit 2aa02b1

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
//////////////////////////////////////////////////////////////////////////////
2+
// Depth First Search (DFS)
3+
// Time: O(m*n)
4+
// Space: O(m*n)
5+
// You can implement either Depth First Search (DFS) or Breadth First Search
6+
// (BFS). The only noticeable impact is the performance cost of the BFS queue
7+
// is higher than the DFS call stack.
8+
//////////////////////////////////////////////////////////////////////////////
9+
10+
/**
11+
* @param {character[][]} board
12+
* @return {void} Do not return anything, modify board in-place instead.
13+
*/
14+
function solve(board) {
15+
16+
const rowLen = board.length;
17+
const colLen = board[0].length;
18+
const lastRow = rowLen - 1;
19+
const lastCol = colLen - 1;
20+
21+
for (let r = 0; r < rowLen; ++r) {
22+
markSeen(r, 0);
23+
markSeen(r, lastCol);
24+
}
25+
for (let c = 1; c < lastCol; ++c) {
26+
markSeen(0, c);
27+
markSeen(lastRow, c);
28+
}
29+
30+
for (let r = 0; r < rowLen; ++r) {
31+
for (let c = 0; c < colLen; ++c) {
32+
switch (board[r][c]) {
33+
case 'O':
34+
board[r][c] = 'X';
35+
break;
36+
case 'A':
37+
board[r][c] = 'O';
38+
break;
39+
}
40+
}
41+
}
42+
43+
/**
44+
* @param {number} r
45+
* @param {number} c
46+
* @return {void}
47+
*/
48+
function markSeen(r, c) {
49+
50+
if (!inBounds(r, c) || board[r][c] !== 'O') {
51+
return;
52+
}
53+
54+
board[r][c] = 'A';
55+
56+
markSeen(r - 1, c);
57+
markSeen(r + 1, c);
58+
markSeen(r, c - 1);
59+
markSeen(r, c + 1);
60+
}
61+
62+
/**
63+
* @param {number} r
64+
* @param {number} c
65+
* @return {boolean}
66+
*/
67+
function inBounds(r, c) {
68+
return r >= 0 && c >= 0 && r < rowLen && c < colLen;
69+
}
70+
}

0 commit comments

Comments
 (0)