leetcode 130 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

dfs 会 破 栈 !!!!
只能用 bfs 。。。。
简单搜索就做了一下午,神马pair,vector...各种不懂
好不容易写出来,结果RE,以后还是不要嫌麻烦了。
第一道题,记录一下。

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<vector>
 4 #include<queue>
 5 
 6 using namespace std;
 7 
 8 //int dx[4]={0,0,1,-1};
 9 //int dy[4]={1,-1,0,0};
10 
11 class Solution {
12 public:
13     int n,m;
14     const int dx[4]={0,0,1,-1}, dy[4]={1,-1,0,0};
15     bool judge( int x, int y ,vector<vector<char> > &board)
16     {
17         if( x >=n || y >=m || x<0 || y <0 || board[x][y] !='O' )
18             return false;
19         board[x][y]='&';
20         return true;
21     }
22     void bfs(int x, int y, vector <vector<char > > &board)
23     {
24         queue< pair<int,int> >q;
25         if( !judge( x, y, board ) ) return ;
26         q.push( pair<int, int>(x,y));
27         while( !q.empty() )
28         {
29             int xx,yy,v,w;
30             v=q.front().first;
31             w=q.front().second;
32             q.pop();
33             for(int i=0;i<4;i++)
34             {
35                 xx=v+dx[i];
36                 yy=w+dy[i];
37                 if( ! judge( xx, yy,board) ) continue;
38                 q.push( pair<int,int>(xx,yy));
39             }
40         }
41 
42     }
43 
44     void solve(vector<vector<char> > &board) {
45         /******/
46         n=board.size();  if( n<3 ) return ;  ///行数
47         m=board[0].size();  if( m<3 ) return ; ///列数
48         //cout << n << "   " <<m <<endl;
49         for(int i=0;i<m;i++)///第0,n-1行
50         {
51            bfs( 0, i,board);
52            bfs( n-1, i,board);
53         }
54         for(int i=0;i<n;i++)///第0,m-1列
55         {
56            bfs( i, 0,board);
57            bfs( i, m-1,board);
58         }
59         for(int i=0;i<n;i++)
60             for(int j=0;j<m;j++)
61             {
62                 if( board[i][j] == 'O' )  board[i][j]='X';
63                 if( board[i][j] == '&' )  board[i][j]='O';
64             }
65     }
66 };
67 
68 int main( )
69 {
70     char s[100],c;
71     freopen("input.txt","r",stdin);
72     vector <vector<char> > board(4, vector<char>(4));
73     for(int i=0;i<4;i++){
74         scanf("%s",s);
75         for(int j=0;j<4;j++)
76         {
77             c=s[j];
78             board[i][j]=c;
79         }
80     }
81     Solution a;
82     a.solve( board );
83     for(int i=0;i<4;i++)
84     {
85         for(int j=0;j<4;j++)
86         printf("%c",board[i][j]);
87         printf("\n");
88     }
89     return 0;
90 }
View Code

 

posted @ 2015-04-14 16:46  lysr__tlp  阅读(288)  评论(0编辑  收藏  举报