首页 > 编程语言 > 详细

BFS数组,将包围区域‘O'换成’X'

时间:2016-06-29 10:00:23      阅读:204      评论:0      收藏:0      [点我收藏+]

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

 思路:将包围区域的‘o‘变成@ 采用BFS方法遍历,还使用了数组坐标压缩

class Solution {
public:
int max(int a, int b)
{
  return a > b ? a : b;
}
int dir[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
void bfs(vector<vector<char>>&board, int m, int n, int i, int j, int code)
{
  queue<int> q;
  q.push(i*code + j);
  while (!q.empty())
  {
  int tmp = q.front();
  q.pop();
  int row = tmp / code;
  int col = tmp%code;
  for (int k = 0; k < 4; k++)
  {
  if (row + dir[k][0] < m && row + dir[k][0] >= 0 && col + dir[k][1] < n&& col + dir[k][1] >= 0)
  {
  if (board[row + dir[k][0]][col + dir[k][1]] == ‘O‘)
  {
    board[row + dir[k][0]][col + dir[k][1]] = ‘@‘;

    q.push((row + dir[k][0]) * code + col + dir[k][1]);
  }

  }
  }
}

}
void solve(vector<vector<char>>&board)
{
  int m = board.size();
  int n = board[0].size();
  if (m < 3 || n < 3)
    return;
  int code = max(m, n);
  for (int i = 0; i < m; i++)
  {
  for (int j = 0; j < n; j++)
  {
  if (board[i][j] == ‘O‘ && (i == 0 || i == m - 1 || j == 0 || j == n - 1))
  {
    board[i][j] = ‘@‘;
    bfs(board, m, n, i, j, code);
  }
  }
}
  for (int i = 0; i < m; i++)
  {
    for (int j = 0; j < n; j++)
  {
    if (board[i][j] == ‘O‘)
      board[i][j] = ‘X‘;
    else if (board[i][j] == ‘@‘)
      board[i][j] = ‘O‘;
  }
  }
}
};

BFS数组,将包围区域‘O'换成’X'

原文:http://www.cnblogs.com/ranranblog/p/5625789.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!