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



DFS会StackOverFlow,网上有解法说可以用非递归的DFS,http://blog.csdn.net/linhuanmars/article/details/22904855

当然不用DFS的话,就用BFS了。要注意的是:保存一个全局二维数组记录已经遍历过的节点

import java.util.ArrayList;
import java.util.List;

class Point {
	int i, j;
	public Point(int i, int j) {
		this.i = i;
		this.j = j;
	}
}

/*
 * 用BFS
 */
public class Solution {
	boolean f = false;
	int[] diff1 = new int[]{0,0,1,-1};
	int[] diff2 = new int[]{1,-1,0,0};
	boolean[][] marked;
	
    public void solve(char[][] board) {
    	if(board == null || board.length == 0)	return;
    	
    	marked = new boolean[board.length][board[0].length];
    	for(int i=1; i<board.length-1; i++) {
    		for(int j=1; j<board[0].length-1; j++) {
    			if(board[i][j] == 'O' && !marked[i][j])
    				bfs(board, i, j);
    		}
    	}
        
    }
    
	private void bfs(char[][] board, int i, int j) {
		List<Point> list = new ArrayList<Point>();
		List<Point> next = new ArrayList<Point>();
		List<Point> path = new ArrayList<Point>();
		boolean f = true;
		
		marked[i][j] = true;
		list.add(new Point(i, j));
		while(!list.isEmpty()) {
			for(Point p : list) {
				if(p.i == 0 || p.i == board.length-1 || p.j == 0 || p.j == board[0].length-1)	{
					f = false;
				}
				for(int k=0; k<4; k++) {
					int newi = p.i+diff1[k], newj = p.j+diff2[k];
					if(newi >=0 && newi < board.length && 
							newj >=0 && newj < board[0].length &&
							!marked[newi][newj] && board[newi][newj] == 'O') {
						next.add(new Point(newi, newj));
						marked[newi][newj] = true;
					}
				}
			}
			
			if(!list.isEmpty())	path.addAll(list);
			list = next;
			next = new ArrayList<Point>();
		}
		
		if(f) {
			for(Point p : path)
				board[p.i][p.j] = 'X';
			}
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值