Leetcode 130 Surrounded Regions(BFS)

题目连接:Leetcode 130 Surrounded Regions

解题思路:所有与边界连接的点,是不会被包围的,所有以边界点为起始点,进行BFS,所有没有遍历过的点赋值‘X’。

class Solution {
	public:
		void solve(vector<vector<char>>& board) {
			if (board.size() == 0 || board[0].size() == 0) return;
			int m = board.size(), n = board[0].size();

			vector<vector<bool>> graph;
			vector<bool> tmp;
			for (int i = 0; i < n; i++) tmp.push_back(false);
			for (int i = 0; i < m; i++) graph.push_back(tmp);

			queue<pair<int,int>> que;
			for (int i = 0; i < n; i++) {
				que.push(make_pair(0, i));
				que.push(make_pair(m-1, i));
			}

			for (int i = 0; i < m; i++) {
				que.push(make_pair(i, 0));
				que.push(make_pair(i, n-1));
			}
			int dx[] = {0, 1, 0, -1};
			int dy[] = {1, 0, -1, 0};

			while (!que.empty()) {
				int x = que.front().first;
				int y = que.front().second;
				que.pop();

				if (graph[x][y]) continue;
				graph[x][y] = true;

				for (int d = 0; d < 4; d++) {
					int xx = x + dx[d];
					int yy = y + dy[d];
					if (xx < 0 || xx >= m) continue;
					if (yy < 0 || yy >= n) continue;
					if (graph[xx][yy] || board[xx][yy] != board[x][y]) continue;
					que.push(make_pair(xx, yy));
				}
			} 


			for (int i = 0; i < m; i++) {
				for (int j = 0; j < n; j++) {
					if (graph[i][j] == false)
						board[i][j] = 'X';
				}
			}
		}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值