【LeetCode】130. Surrounded Regions

本文介绍了一种解决二维棋盘中'O'字符被'X'字符围捕问题的算法。通过广度优先搜索(BFS),对边界上的'O'进行标记并保留,最终将所有未被标记的'O'转换为'X'。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • Difficulty: Medium

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

Subscribe to see which companies asked this question

分析
广搜。从上下左右四个边界往里走,凡是能碰到的'0',都是跟边界接壤的,应该保留。

BFS,时间复杂度 O(n),空间复杂度 O(n)

class Solution {
public:
	void solve(vector<vector<char>> &board) {
		if (board.empty()) return;
		const int m = board.size();
		const int n = board[0].size();
		for (int i = 0; i < n; i++) {
			bfs(board, 0, i);
			bfs(board, m - 1, i);
		}
		for (int j = 1; j < m - 1; j++) {
			bfs(board, j, 0);
			bfs(board, j, n - 1);
		}
		for (int i = 0; i < m; i++)
			for (int j = 0; j < n; j++)
				if (board[i][j] == 'O')
					board[i][j] = 'X';
				else if (board[i][j] == '+')
					board[i][j] = 'O';
	}
private:
	void bfs(vector<vector<char>> &board, int i, int j) {
		typedef pair<int, int> state_t;
		queue<state_t> q;
		const int m = board.size();
		const int n = board[0].size();
		auto state_is_valid = [&](const state_t &s) {
			const int x = s.first;
			const int y = s.second;
			if (x < 0 || x >= m || y < 0 || y >= n || board[x][y] != 'O')
				return false;
			return true;
		};
		auto state_extend = [&](const state_t &s) {
			vector<state_t> result;
			const int x = s.first;
			const int y = s.second;
			const state_t new_states[4] = { { x - 1,y },{ x + 1,y },
			{ x,y - 1 },{ x,y + 1 } };
			for (int k = 0; k < 4; ++k) {
				if (state_is_valid(new_states[k])) {
					board[new_states[k].first][new_states[k].second] = '+';
					result.push_back(new_states[k]);
				}
			}
			return result;
		};
		state_t start = { i, j };
		if (state_is_valid(start)) {
			board[i][j] = '+';
			q.push(start);
		}
		while (!q.empty()) {
			auto cur = q.front();
			q.pop();
			auto new_states = state_extend(cur);
			for (auto s : new_states) q.push(s);
		}
	}
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值