面试题41:包围区域

  包围区域是一个典型的DFS的题目。大意是一个二维数组中存在字符'X'和'O',将被'X'包围的'O'全部变为'X'。具体做法是从数组的边界上为'O'的起点开始DFS,将DFS过程中遇到的字符标记为'Y'。然后遍历二维数组,将'Y'的变为'O',其余为'X'即可。

题目描述:

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
 1 class Solution {
 2 public:
 3     void dfs(int x,int y,vector<vector<char>>& board){
 4         if(x<0 || x >= board.size()) return;
 5         if(y<0 || y >= board[0].size()) return;
 6         if(board[x][y] == 'O'){
 7             board[x][y] = 'Y';
 8         }else{
 9             return;
10         }
11         dfs(x+1,y,board);
12         dfs(x-1,y,board);
13         dfs(x,y+1,board);
14         dfs(x,y-1,board);
15 
16     }
17     void solve(vector<vector<char>> &board) {
18         int m = board.size();
19         int n = board[0].size();
20         for(int i=0;i<m;i++){
21             for(int j=0;j<n;j++){
22                 if((i==0 || i== m-1 || j== 0 || j == n-1) && board[i][j] == 'O' ){
23                     dfs(i,j,board);
24                 }
25             }
26         }
27 
28         for(int i=0;i<m;i++){
29             for(int j=0;j<n;j++){
30                 if(board[i][j] == 'Y'){
31                     board[i][j] = 'O';
32                 }else{
33                     board[i][j] = 'X';
34                 }
35             }
36         }
37     }
38 };

 

posted @ 2017-06-06 09:56  wxquare  阅读(420)  评论(0编辑  收藏  举报