LeetCode: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
 1 class Solution {
 2 public:
 3     void solve(vector<vector<char>>& board) {
 4         int m=board.size();
 5         int n=board[0].size();
 6         //先对边上的节点DFS
 7         for(int i=0;i<m;++i)
 8             for(int j=0;j<n;++j)
 9             {   
10                 //把边边的映射成为1
11                 if(i==0||j==0|i==m-1||j==n-1&&board[i][j]=='0')
12                     DFS(board,i,j,'1');
13                 else
14                     continue;
15             }
16             
17        //再把剩下的0联通的映射成为x
18        
19        for(int i=0;i<m;++i)
20         for(int j=0;j<n;++j)
21             if(board[i][j]=='0')
22                 DFS(board,i,j,'x');
23         
24         //再把1的反转为x
25         for(int i=0;i<m;++i)
26             for(int j=0;j<n;++j)
27                 if(board[i][j]=='1')
28                     board[i][j]=='0';        
29     }
30     
31     void DFS(vector<vector<char>> &board,int x,int y,char c)
32     {
33         if(x<0||y<0||x>=board.size()||y>=board[0].size())
34             return;
35         
36         //把所有的都映射成为1
37         if(board[x][y]=='0')
38         {
39             board[x][y]=c;
40             DFS(board,x-1,y);
41             DFS(board,x+1,y);
42             DFS(board,x,y-1);
43             DFS(board,x,y+1);
44         }
45         
46     }
47 };

 

posted @ 2015-08-26 11:08  尾巴草  阅读(153)  评论(0编辑  收藏  举报