Leetcode Surrounded Regions 解题报告
2014-02-15 20:57
357 查看
http://oj.leetcode.com/problems/surrounded-regions/
Given a 2D board containing 'X' and '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
题意说明:输入一个二维矩阵,把所有被X包围的O都变成X,但如果某个O在边(角)上,则所有与这个O相连的O都不能变成X。
解题思路:从边上的O开始便利,所有与边上O相连的O都不能变成X(可暂时变为Y),之后再重新遍历一遍矩阵把所有O变成X,所有Y变成O。
需要注意的是,本题使用DFS也会出现栈溢出,只能使用BFS。从队列中取出一个节点,把该节点变为Y,如果该节点的四周有还未变为Y的O,则这些节点放入队列。
AC代码:
Given a 2D board containing 'X' and '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
题意说明:输入一个二维矩阵,把所有被X包围的O都变成X,但如果某个O在边(角)上,则所有与这个O相连的O都不能变成X。
解题思路:从边上的O开始便利,所有与边上O相连的O都不能变成X(可暂时变为Y),之后再重新遍历一遍矩阵把所有O变成X,所有Y变成O。
需要注意的是,本题使用DFS也会出现栈溢出,只能使用BFS。从队列中取出一个节点,把该节点变为Y,如果该节点的四周有还未变为Y的O,则这些节点放入队列。
AC代码:
class Pair { int x; int y; Pair(int x,int y) { this.x = x; this.y = y; } } public class Solution { public void solve(char[][] board) { if(board==null||board.length==0) { return; } Queue queue = new LinkedList<Pair>(); //对所有在边上的O节点进行BFS for(int i=0;i<board.length;i++) { for(int j=0;j<board[0].length;j++) { if(i==0||i==(board.length-1)||j==0||j==(board[0].length-1)) { if(board[i][j]=='O') { Pair position = new Pair(i,j); queue.add(position); } } } } int x1,y1; //BFS while(!queue.isEmpty()) { Pair position = (Pair)queue.poll(); x1 = position.x; y1 = position.y; if(board[x1][y1]=='Y') { continue; } //四个方向查找,找到为'O'的节点放入队列中。 //left board[x1][y1] = 'Y'; int index = x1 - 1; if(index>=0&&board[index][y1]=='O') { queue.add(new Pair(index,y1)); } //right index = x1 + 1; if(index<board.length&&board[index][y1]=='O') { queue.add(new Pair(index,y1)); } //up index = y1 + 1 ; if(index<board[0].length&&board[x1][index]=='O') { queue.add(new Pair(x1,index)); } //down index = y1 - 1; if(index>=0&&board[x1][index]=='O') { queue.add(new Pair(x1,index)); } } for(int i=0;i<board.length;i++) { for(int j=0;j<board[0].length;j++) { if(board[i][j]=='Y') { board[i][j] = 'O'; } else { if(board[i][j]=='O') { board[i][j] = 'X'; } } } } return; } }
相关文章推荐
- 编码相关了解
- myeclipse8.5 启动时不弹出工作空间的选择
- NVelocity入门,为服务器与客户端传输xml数据,实现Ajax通信铺平道路
- 我的苹果开发学习笔记
- mac系统如何显示和隐藏文件
- 关于考研的几个问题
- 浅析贪心算法中“最优数对”问题
- HDU 2196
- SSH Secure Shell Client用密钥认证登录linux服务器
- 【转】敏捷开发流程
- 《学习OpenCV》练习7-6
- javascript网上程序代写
- css样式大全
- 常用的正则表达式
- 简述UML之类图
- FatMouse' Trade
- Matlab并行编程<cellfun & arrayfun>
- hibernate连接Oracle数据库出现关闭的连接问题
- ASIDownload下载显示的用法
- 银行总账