Leetcode 130: Surrounded Regions

Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

For example,

X X X X
X O O X
X X O X
X O X X

 

After running your function, the board should be:

X X X X
X X X X
X X X X
X O X X


 1 public class Solution {
 2     private int[,] directions = new int[,] {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
 3     private const char mark = 'A';
 4     
 5     public void Solve(char[,] board) {
 6         int rows = board.GetLength(0), cols = board.GetLength(1);
 7         
 8         if (rows <= 1 || cols <= 1) return;
 9         
10         for (int i = 0; i < rows; i++)
11         {
12             if (board[i, 0] == 'O')
13             {
14                 DFS(board, rows, cols, i, 0);
15             }
16             
17             if (board[i, cols - 1] == 'O')
18             {
19                 DFS(board, rows, cols, i, cols - 1);
20             }
21         }
22         
23         for (int i = 0; i < cols; i++)
24         {
25             if (board[0, i] == 'O')
26             {
27                 DFS(board, rows, cols, 0, i);
28             }
29             
30             if (board[rows - 1, i] == 'O')
31             {
32                 DFS(board, rows, cols, rows - 1, i);
33             }
34         }
35        
36         for (int i = 0; i < rows; i++)
37         {
38             for (int j = 0; j < cols; j++)
39             {
40                 if (board[i, j] == mark)
41                 {
42                     board[i, j] = 'O';
43                 }
44                 else if (board[i, j] == 'O')
45                 {
46                     board[i, j] = 'X';
47                 }
48             }
49         }
50     }
51     
52     private void DFS(char[,] board, int rows, int cols, int row, int col)
53     {
54         if (row < 0 || row >= rows || col < 0 || col >= cols || board[row, col] != 'O')
55         {
56             return;
57         }
58         
59         board[row, col] = mark;
60         
61         for (int i = 0; i < directions.GetLength(0); i++)
62         {
63             int r = row + directions[i, 0], c = col + directions[i, 1];
64             
65             DFS(board, rows, cols, r, c);
66         }
67     }
68 }

 

转载于:https://www.cnblogs.com/liangmou/p/7877020.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值