Problem:

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
/**
* Created by sunny on 7/24/17.
*/
import java.util.*;
public class Solution {
public void solve(char[][] board) {
if (board == null || board.length == 0) {
return;
}
//首先将第一列和最后一列的O变为#
for(int i = 0;i<board.length;i++){
//这是按行遍历
fill(board, i, 0);
fill(board, i, board[i].length-1);
}
//将第一行和最后一行的O变为#
for (int i = 0; i < board[0].length; i++) {
fill(board, 0, i);
fill(board, board.length-1, i);
}
//遍历整个数组,o变为X,#变为O
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == 'O') {
board[i][j] = 'X';
}else if(board[i][j] == '#'){
board[i][j] ='O';
}
}
}
}
private void fill(char[][] board,int row,int col) {
if (board[row][col] == 'X') {
return ;
}
board[row][col] = '#';
Queue<Integer> queue = new LinkedList<>();
//需要将元素的位置存储到 队列中 行和列
int code = row * board[0].length + col;
queue.add(code);
while(!queue.isEmpty()){
//找到这个元素
int temp = queue.poll();
//第几行
int i = temp/board[0].length;
//第几列
int j = temp%board[0].length;
//看这个元素的四个周是不是O,上边
if(i-1>=0&&board[i-1][j] == 'O'){
board[i-1][j] = '#';
queue.add((i-1)*board[0].length+j);
}
if (i+1<board.length&&board[i+1][j] == 'O') {
board[i+1][j] = '#';
queue.add((i+1)*board[0].length+j);
}
if (j-1>=0&&board[i][j-1] == 'O') {
board[i][j-1] = '#';
queue.add(i*board[0].length+j-1);
}
if (j+1<board[0].length&&board[i][j+1]=='O') {
board[i][j+1] = '#';
queue.add(i*board[0].length+j+1);
}
}
} public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[][] board = new char[][]{
{'X','X','X','X'},
{'X','O','O','O'},
{'X','O','X','X'},
{'X','X','X','X'}
};
Solution solution = new Solution();
solution.solve(board);
for(int i=0;i<board.length;i++){
for(int j=0;j<board[i].length;j++){
System.out.print(board[i][j]);
}
System.out.println();
}
}
}

采用广度优先遍历求解。---队列的应用

最新文章

  1. 分享公司DAO层数据库结果映射到对象的方法
  2. $compile
  3. Quartus II 增量编译
  4. [LeetCode] Remove Duplicates from Sorted Array
  5. Openstack Murano(kilo)二次开发之添加Volume
  6. CoreLoation
  7. JAVA基础知识之List集合
  8. XML约束——Schema约束
  9. idea项目部署
  10. 使用SCP在命令行传输文件
  11. Linux shell 脚本攻略之正则表达式入门
  12. Ambry: LinkedIn’s Scalable Geo-Distributed Object Store
  13. EqualsBuilder和HashCodeBuilder(重写equal和hashcode)
  14. a标签的背景图在ie8下显示问题
  15. Facebook的手游出海之道
  16. sprintf mfc
  17. 使用vs中的工具进行架构比较
  18. perl Mail::Sender模块发送邮件
  19. exports和module.exports的区别
  20. cmake编译opencv时指定cuda版本

热门文章

  1. python究竟要不要使用多线程
  2. 1151 LCA in a Binary Tree(30 分)
  3. 神秘常量!用0x077CB531计算末尾0的个数,32位数首位相连
  4. 试用 Eagle 9.1
  5. phoneGap入门教程
  6. [转]java 中的序列化是什么意思?有什么好处?
  7. 备份Ubuntu系统
  8. [置顶] if语句的陷阱
  9. iOS中的数据存储
  10. 2015.1.15 利用Oracle函数插入表结构 Bulk collect into 不用循环,简洁高效