From 6dc683dc045c219ec42d29d5ac263d182f68e75d Mon Sep 17 00:00:00 2001 From: Hassan Mehmood Date: Thu, 3 Oct 2024 11:42:41 +0500 Subject: [PATCH] Time: 76 ms (63.1%), Space: 55.6 MB (42.06%) - LeetHub --- .../0130-surrounded-regions.js | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 0130-surrounded-regions/0130-surrounded-regions.js diff --git a/0130-surrounded-regions/0130-surrounded-regions.js b/0130-surrounded-regions/0130-surrounded-regions.js new file mode 100644 index 0000000..10ba627 --- /dev/null +++ b/0130-surrounded-regions/0130-surrounded-regions.js @@ -0,0 +1,55 @@ +/** + * @param {character[][]} board + * @return {void} Do not return anything, modify board in-place instead. + */ +var solve = function (board) { + let rows = board.length + let cols = board[0].length + + + var dfs = function (start, end) { + if (start < 0 || start >= rows || end < 0 || end >= cols || board[start][end] != "O") { + return + } + board[start][end] = "B" + + for (let [r, c] of [[-1, 0], [1, 0], [0, -1], [0, 1]]) { + let x = r + start + let y = c + end + dfs(x, y) + + } + } + + + + // check all rows + for (let i = 0; i < rows; i++) { + if (board[i][0] == "O") { + dfs(i, 0) + } + if (board[i][cols - 1] == "O") { + dfs(i, cols - 1) + } + } + for (let i = 0; i < cols; i++) { + if (board[0][i] == "O") { + dfs(0, i) + } + if (board[rows - 1][i] == "O") { + dfs(rows - 1, i) + } + } + + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + if (board[i][j] == "O") { + board[i][j] = "X" + } + else if (board[i][j] == 'B') { + board[i][j] = "O" + } + } + } + return board +}; \ No newline at end of file