From 73c06613f7f9614df170667aa6bef87f0dcca3d4 Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 15 Jan 2024 17:24:43 +0800 Subject: [PATCH] =?UTF-8?q?Update=200130.=E8=A2=AB=E5=9B=B4=E7=BB=95?= =?UTF-8?q?=E7=9A=84=E5=8C=BA=E5=9F=9F.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0130.被围绕的区域.md | 52 +++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/problems/0130.被围绕的区域.md b/problems/0130.被围绕的区域.md index 8014c0c8..e2185a17 100644 --- a/problems/0130.被围绕的区域.md +++ b/problems/0130.被围绕的区域.md @@ -561,6 +561,58 @@ function solve(board) { } ``` +### Go + +```dfs +var DIRECTIONS = [4][2]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}} + +func solve(board [][]byte) { + rows, cols := len(board), len(board[0]) + // 列 + for i := 0; i < rows; i++ { + if board[i][0] == 'O' { + dfs(board, i, 0) + } + if board[i][cols-1] == 'O' { + dfs(board, i, cols-1) + } + } + // 行 + for j := 0; j < cols; j++ { + if board[0][j] == 'O' { + dfs(board, 0, j) + } + if board[rows-1][j] == 'O' { + dfs(board, rows-1, j) + } + } + + for _, r := range board { + for j, c := range r { + if c == 'A' { + r[j] = 'O' + } + if c == 'O' { + r[j] = 'X' + } + } + } +} + +func dfs(board [][]byte, i, j int) { + board[i][j] = 'A' + for _, d := range DIRECTIONS { + x, y := i+d[0], j+d[1] + if x < 0 || x >= len(board) || y < 0 || y >= len(board[0]) { + continue + } + if board[x][y] == 'O' { + dfs(board, x, y) + } + } +} +``` +