반응형
SMALL
문제
Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Example 1:
Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
Explanation: Notice that an 'O' should not be flipped if:
- It is on the border, or
- It is adjacent to an 'O' that should not be flipped.
The bottom 'O' is on the border, so it is not flipped.
The other three 'O' form a surrounded region, so they are flipped.
Example 2:
Input: board = [["X"]]
Output: [["X"]]
Constraints:
- m == board.length
- n == board[i].length
- 1 <= m, n <= 200
- board[i][j] is 'X' or 'O'.
코드
/**
* @param {character[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
function solve(board) {
if (!board.length) return;
for(let i = 0; i < board.length; i++) {
for(let j = 0; j < board[0].length; j++) {
if(board[i][j] == 'O' && (i === 0 || i === board.length - 1 || j === 0 || j === board[0].length - 1)) {
mark(board, i, j)
}
}
}
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[0].length; j++) {
// change the rest of O to X
if (board[i][j] === 'O') board[i][j] = 'X';
// change temporary # back to O
if (board[i][j] === '#') board[i][j] = 'O';
}
}
}
function mark(board, i ,j) {
if (i < 0 || i > board.length - 1 || j < 0 || j > board[0].length - 1) return;
if (board[i][j] !== 'O') return;
// O 중에 X로 안바꿀애들
board[i][j] = '#';
mark(board, i - 1, j);
mark(board, i + 1, j);
mark(board, i, j - 1);
mark(board, i, j + 1);
}
반응형
LIST
'Coding Interview' 카테고리의 다른 글
[LeetCode] BFS - 285. Inorder Successor in BST (0) | 2022.09.27 |
---|---|
[LeetCode] BFS-DFS 116. Populating Next Right Pointers in Each Node (0) | 2022.09.27 |
[LeetCode] DFS - 94. Binary Tree Inorder Traversal (0) | 2022.09.27 |
[LeetCode] BFS-DFS 104. Maximum Depth of Binary Tree (0) | 2022.09.27 |
[LeetCode] BFS 210. Course Schedule II (feat. 위상정렬) (0) | 2022.09.26 |