Surrounded Regions--LeetCode

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.

例如:

输入:

X X X X

X O O X

X X O X

X O X X

输出:

X X X X

X X X X

X X X X

X O X X

分析:

典型的BFS题目。遍历每个字符,如果是“O”,则从当前字符开始BFS遍历,如果周围也是“O”则加入当前遍历的队列,知道遍历完所有相邻的“O”,于此同时,判断每个O是否是被包围的,只有由一个O是没有被包围的,则当前遍历的O的集合都是没有被包围的,因为这些O都是相连的。

对于BFS不是很熟悉,这里看一个例子熟悉一下。

public class Solution {
public static void solve(char[][] board) {
    Queue<Integer> queue = new LinkedList<Integer>();
    if (board == null || board.length == 0)
      return;
    int m = board.length;
    int n = board[0].length;
    boolean visited[][] = new boolean[m][n];
    int dir[][] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {

        //以下是标准的BFS搜索,用visitedPoints记录访问的O
        if (board[i][j] == 'O' && !visited[i][j]) {
          boolean surounned = true;
          List<Integer> visitedPoints = new ArrayList<Integer>();
          queue.add(i * n + j);
          visited[i][j] = true;
          while (queue.size() > 0) {
            int point = queue.poll();
            visitedPoints.add(point);
            int x = point/n;
            int y = point%n;
            for (int k = 0; k < 4; k++) {
              int nextx = x + dir[k][0];
              int nexty = y + dir[k][1];
              if (nextx >= 0 && nextx < m && nexty >= 0 && nexty < n) {
                if (board[nextx][nexty] == 'O' && !visited[nextx][nexty])
                  queue.add(nextx * n + nexty);
                visited[nextx][nexty] = true;
              } else {
                surounned = false;
              }
            }
          }

          //如果当前遍历到的O是被包围的
          if (surounned) {
            for (int p : visitedPoints)
              board[p / n][p % n] = 'X';
          }
        }
      }
    }
  }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值