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: 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.
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'.
Solution
Approach #0: BFS
var ( dx = []int{0, 1, 0, -1} dy = []int{1, 0, -1, 0})funcsolve(board [][]byte) { m, n :=len(board), len(board[0])var queue [][]intfor i :=0; i < n; i++ {if board[0][i] !='X' { board[0][i] ='-' queue =append(queue, []int{0, i}) }if board[m-1][i] !='X' { board[m-1][i] ='-' queue =append(queue, []int{m -1, i}) } }for i :=1; i < m-1; i++ {if board[i][0] !='X' { board[i][0] ='-' queue =append(queue, []int{i, 0}) }if board[i][n-1] !='X' { board[i][n-1] ='-' queue =append(queue, []int{i, n -1}) } }forlen(queue) >0 { x, y := queue[0][0], queue[0][1] queue = queue[1:]for i :=0; i <4; i++ { xx, yy := x+dx[i], y+dy[i]if xx >=0&& xx < m && yy >=0&& yy < n && board[xx][yy] =='O' { queue =append(queue, []int{xx, yy}) board[xx][yy] ='-' } } }for i :=0; i < m; i++ {for j :=0; j < n; j++ {if board[i][j] =='-' { board[i][j] ='O' } else { board[i][j] ='X' } } }}
Approach #1: DFS
var ( dx = []int{0, 1, 0, -1} dy = []int{1, 0, -1, 0})funcsolve(board [][]byte) { m, n :=len(board), len(board[0])var dfs func(board [][]byte, x, y int) dfs =func(board [][]byte, x, y int) {if x <0|| x >= m || y <0|| y >= n || board[x][y] !='O' {return } board[x][y] ='-'for i :=0; i <4; i++ { xx, yy := x+dx[i], y+dy[i]dfs(board, xx, yy) } }for i :=0; i < n; i++ {dfs(board, 0, i)dfs(board, m-1, i) }for i :=1; i < m-1; i++ {dfs(board, i, 0)dfs(board, i, n-1) }for i :=0; i < m; i++ {for j :=0; j < n; j++ {if board[i][j] =='-' { board[i][j] ='O' } else { board[i][j] ='X' } } }}
Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.
The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).
Example 1:
Input: graph = [[1,2],[3],[3],[]]
Output: [[0,1,3],[0,2,3]]
Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.