> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/130.-surrounded-regions-medium.md).

# 130. Surrounded Regions (Medium)

## 1.問題

* 給予一個有著'X', 'O'的2D版, 找出所有由X包圍的區域

![](/files/-LIU8xYk2GhowLG71Ng1)

## 2.想法

* 用DFS將外圍的'O'有碰到的''O都改為'A', 並掃描所有的elements, 將'A'改為'O'

## 3.程式碼

```
class Solution {
public:
    void solve(vector<vector<char>>& board) {
        if (board.size() == 0) {
            return;
        }
        int h = board.size(), w = board[0].size();
        
        for (int i = 0; i < h; i++) {
            check(board, i, 0);
            check(board, i, w - 1);
        }
        
        for (int i = 0; i < w; i++) {
            check(board, 0, i);
            check(board, h - 1, i);
        }
        
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                if (board[i][j] == 'A') {
                    board[i][j] = 'O';
                } else {
                    board[i][j] = 'X';
                }
            }
        }
    }
private:
    void check(vector<vector<char>>& board, int r, int c) {
        if (r >= 0 && r < board.size() && 
            c >= 0 && c < board[0].size() &&
            board[r][c] == 'O') {
            board[r][c] = 'A';
            check(board, r + 1, c);
            check(board, r - 1, c);
            check(board, r, c + 1);
            check(board, r , c - 1);
        }
    }
};
```

## 4.Performance

![](/files/-LIUD8b-Bu3j10Ls9L7J)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/130.-surrounded-regions-medium.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
