LeetCode Surrounded Regions

Description:

Given a char[][] graph, with character 'X' or 'O', we need to replace any 'O' with 'X' if 'O' is surrounded by 'O'.

Solution:

We may link all the 'O' regions and find that only those linked with the edge of char[][] will stay 'O', while others will become 'X', so we just need to find the 'O' linked with the edge part of char[][].

import java.util.LinkedList;

public class Solution {
	int dir[][] = { { 1, -1, 0, 0 }, { 0, 0, 1, -1 } };
	int n, m;

	public void solve(char[][] board) {
		n = board.length;
		if (n == 0)
			return;
		m = board[0].length;
		boolean vis[][] = new boolean[n][m];
		LinkedList<node> queue = new LinkedList<node>();

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (board[i][j] == 'O'
						&& (i == 0 || i == n - 1 || j == 0 || j == m - 1)) {
					queue.add(new node(i, j));
				}
			}
		}

		node temp;
		int x, y, tx, ty;
		while (!queue.isEmpty()) {
			temp = queue.poll();
			x = temp.x;
			y = temp.y;
			vis[x][y] = true;
			for (int i = 0; i < 4; i++) {
				tx = x + dir[0][i];
				ty = y + dir[1][i];
				if (valid(tx, ty) && !vis[tx][ty] && board[tx][ty] == 'O') {
					queue.add(new node(tx, ty));
				}
			}
		}

		for (int i = 0; i < n; i++)
			for (int j = 0; j < m; j++)
				if (!vis[i][j])
					board[i][j] = 'X';

	}

	boolean valid(int x, int y) {
		if (x >= 0 && x < n && y >= 0 && y < m)
			return true;
		return false;
	}

	class node {
		int x, y;

		node(int x, int y) {
			this.x = x;
			this.y = y;
		}
	}

	public static void main(String[] args) {
		Solution s = new Solution();
		char[][] map = new char[4][4];
		map[0][1] = 'O';
		s.solve(map);
		for (int i = 0; i < 4; i++) {
			for (int j = 0; j < 4; j++)
				System.out.print(map[i][j] + " ");
			System.out.println();
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值