LeetCode-130. Surrounded Regions (JAVA)(环绕区域)

该博客介绍了LeetCode第130题《环绕区域》的解决方法,主要探讨如何使用Java实现,包括原始版、改进版和递归版的解决方案。文章通过BFS策略,讨论如何翻转包围的'O'字符以标记被包围的区域,并给出了示例结果。
摘要由CSDN通过智能技术生成

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

因为最外层的不会被包围,那如果最外层某个位置为O,那么紧挨着它的所有位置的O都不会被包围,因此,实际上是使用BFS的方法,利用一个队列的数据结构。

原始版:

	class Node {
		int row;
		int col;

		public Node(int row, int col) {
			this.row = row;
			this.col = col;
		}
	}

	public void solve(char[][] board) {
		if (board == null || board.length == 0)
			return;
		int m = board.length;
		int n = board[0].length;
		boolean[][] visited = new boolean[m][n];
		Queue<Character> q = new LinkedList<>();
		// 第一行和最后一行
		for (int i = 0; i < n; i++) {
			if (!visited[0][i] && board[0][i] == 'O')
				bfs(board, 0, i, m, n, visited);
			if (!visited[m - 1][i] && board[m - 1][i] == '
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值