其他分享
首页 > 其他分享> > leetcode 130. 被围绕的区域

leetcode 130. 被围绕的区域

作者:互联网

 

 

DFS不一定每次都要从里到外,也可能从外到里  找出边界O然后找到与他相连的标记成A,别的O就是被包围的O。

 1 class Solution {
 2 public:
 3     int n, m;
 4 
 5     void dfs(vector<vector<char>>& board, int x, int y) {
 6         if (x < 0 || x >= n || y < 0 || y >= m || board[x][y] != 'O') {
 7             return;
 8         }
 9         board[x][y] = 'A';
10         dfs(board, x + 1, y);
11         dfs(board, x - 1, y);
12         dfs(board, x, y + 1);
13         dfs(board, x, y - 1);
14     }
15 
16     void solve(vector<vector<char>>& board) {
17         n = board.size();
18         if (n == 0) {
19             return;
20         }
21         m = board[0].size();
22         for (int i = 0; i < n; i++) {
23             dfs(board, i, 0);
24             dfs(board, i, m - 1);
25         }
26         for (int i = 1; i < m - 1; i++) {
27             dfs(board, 0, i);
28             dfs(board, n - 1, i);
29         }
30         for (int i = 0; i < n; i++) {
31             for (int j = 0; j < m; j++) {
32                 if (board[i][j] == 'A') {
33                     board[i][j] = 'O';
34                 } else if (board[i][j] == 'O') {
35                     board[i][j] = 'X';
36                 }
37             }
38         }
39     }
40 };
View Code

 

标签:vector,int,围绕,dfs,++,130,board,leetcode,size
来源: https://www.cnblogs.com/libin123/p/14615752.html