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: Surrounded regions should not be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.
Agr kise region ko save hona hai toh border location pr hona padega usko.
package pep.Day40;
public class LeetCode_130_Surrounded_Regions {
public static void main(String[] args) {
char[][] board = {{'X', 'X', 'X', 'X'}, {'X', 'O', 'O', 'X'}, {'X', 'X', 'O', 'X'}, {'X', 'O', 'X', 'X'}};
solve(board);
}
public static void solve(char[][] board) {
for (int i = 0; i < board.length; i++)
for (int j = 0; j < board[0].length; j++) {
if (i == 0 || j == 0 || i == board.length - 1 || j == board[0].length - 1)
if (board[i][j] == 'O')
consume(board, i, j);
}
for (int i = 0; i < board.length; i++)
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == 'O')
board[i][j] = 'X';
else if (board[i][j] == '#')
board[i][j] = 'O';
}
System.out.println(board);
}
private static void consume(char[][] board, int i, int j) {
if (i < 0 || j < 0 || i == board.length || j == board[0].length || board[i][j] != 'O')
return;
board[i][j] = '#';
int[][] dirns = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
for (int[] dir : dirns) {
int x = dir[0] + i;
int y = dir[1] + j;
consume(board, x, y);
}
}
}
No comments:
Post a Comment