码迷,mamicode.com
首页 > 其他好文 > 详细

Problem Surrounded Regions

时间:2014-07-07 16:20:26      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   strong   cti   

Problem Description:

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

 

 

 Solution:
 1  public void solve(char[][] board) {
 2         Stack<Integer> sx  = new Stack<Integer>();
 3         Stack<Integer> sy = new Stack<Integer>();
 4 
 5         if (board == null || board.length == 0) return;
 6         if (board[0].length == 0) return;
 7 
 8         int row = board.length;
 9         int col  = board[0].length;
10 
11         for (int i = 0; i < row; i++) {
12             if (board[i][0] == ‘O‘) {
13                 sx.push(i);
14                 sy.push(0);
15             }
16 
17             if (board[i][col - 1] == ‘O‘) {
18                 sx.push(i);
19                 sy.push(col - 1);
20             }
21         }
22 
23         for (int j = 0; j < col; j++) {
24             if (board[0][j] == ‘O‘) {
25                 sx.push(0);
26                 sy.push(j);
27             }
28 
29             if (board[row - 1][j] == ‘O‘) {
30                 sx.push(row - 1);
31                 sy.push(j);
32             }
33         }
34         while (! sx.isEmpty()) {
35             int x = sx.pop();
36             int y = sy.pop();
37 
38             board[x][y] = ‘#‘;
39 
40             if (y > 0 && board[x][y - 1] == ‘O‘) {
41                 sx.push(x);
42                 sy.push(y - 1);
43             }
44 
45             if (y < col - 1 && board[x][y + 1] == ‘O‘) {
46                 sx.push(x);
47                 sy.push(y + 1);
48             }
49 
50             if (x > 0 && board[x - 1][y] == ‘O‘) {
51                 sx.push(x - 1);
52                 sy.push(y);
53             }
54             if (x < row - 1 && board[x + 1][y] == ‘O‘) {
55                 sx.push(x + 1);
56                 sy.push(y);
57             }
58 
59         }
60         for (int i = 0; i < row; i++) 
61             for (int j = 0; j < col; j++) {
62                 if (board[i][j] == ‘#‘) {
63                     board[i][j]= ‘O‘;
64                 } else {
65                     board[i][j] = ‘X‘;
66                 }
67             }
68 
69     }

 

Problem Surrounded Regions,布布扣,bubuko.com

Problem Surrounded Regions

标签:des   style   blog   color   strong   cti   

原文地址:http://www.cnblogs.com/liew/p/3815097.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!