leetcode Surrounded Regions

作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4051776.html

题目链接:leetcode Surrounded Regions

对于每个边缘的'O'进行广度优先遍历,把他和与其相连接的'O'修改成'M'。这些被修改的点会保持自己的'O',而其他的'O'点就是被'X'包围的点,把他们修改为'X'。

使用如果使用dfs方法,在对于大数据时由于递归层数过多会爆栈,所以该题需要使用bfs。

代码如下:

 1 class Solution {
 2 public:
 3 void bfs(vector<vector<char>> &board, int x, int y)
 4 {
 5     queue<pair<int, int>> qu;
 6     qu.push(make_pair(x, y));
 7     while( qu.size() > 0 )
 8     {
 9         pair<int, int> tmp = qu.front();
10         qu.pop();
11         if( tmp.first >= 0 && tmp.first < board.size() && tmp.second >= 0 && tmp.second < board[0].size() && board[tmp.first][tmp.second] == 'O' )
12         {
13             board[tmp.first][tmp.second] = 'M';
14             qu.push(make_pair(tmp.first, tmp.second+1));
15             qu.push(make_pair(tmp.first, tmp.second-1));
16             qu.push(make_pair(tmp.first+1, tmp.second));
17             qu.push(make_pair(tmp.first-1, tmp.second));
18         }
19     }
20 }
21 void solve(vector<vector<char>> &board) 
22 {
23     if(board.size() <= 2 || board[0].size() <= 2) return;
24     int row = board.size();
25     int col = board[0].size();
26     for( int i = 0 ; i < row ; i++ )
27     {
28         if( board[i][0] == 'O' ) bfs(board, i, 0);
29         if( board[i][col-1] == 'O' ) bfs(board, i, col-1);
30     }
31     for( int i = 1 ; i < col-1 ; i++ )
32     {
33         if( board[0][i] == 'O' ) bfs(board, 0, i);
34         if( board[row-1][i] == 'O' ) bfs(board, row-1, i);
35     }
36     for( int i = 0 ; i < row ; i++ )
37     {
38         for( int j = 0 ; j < col ; j++ )
39         {
40             if( board[i][j] == 'M' )
41             {
42                 board[i][j] = 'O';
43             }
44             else
45             {
46                 board[i][j] = 'X';
47             }
48         }
49     }
50 }
51 };
View Code

 

posted @ 2014-10-26 11:17  jostree  阅读(167)  评论(0编辑  收藏  举报