码迷,mamicode.com
首页 > 其他好文 > 详细

Surrounded Regions

时间:2019-12-22 00:10:57      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:empty   oid   节点   script   for   一个   out   nbsp   int   

Description

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.

Example

Example 1:

Input:
  X X X X
  X O O X
  X X O X
  X O X X
Output:
  X X X X
  X X X X
  X X X X
  X O X X

Example 2:

Input:
  X X X X
  X O O X
  X O O X
  X O X X
Output:
  X X X X
  X O O X
  X O O X
  X O X X
思路:

可以使用BFS或DFS解题.

方法1:

在记录每个节点是否访问过的前提下, 依次从每个 ‘O‘ 开始BFS/DFS, 并且只访问未访问过的 ‘O‘.

如果从一个 ‘O‘ 可以访问到边界, 那么不做任何操作; 否则便将这个 ‘O‘ 可以访问到的所有的 ‘O‘ 替换为 ‘X‘.


方法2:

从每个边界的 ‘O‘ 开始遍历, 只访问 ‘O‘, 先都暂时设置为 ‘T‘ 或其他字符.

遍历结束之后, 将剩下的 ‘O‘ 替换为 ‘X‘ 然后再将 ‘T‘ 还原即可.

public class Solution {

    public void surroundedRegions(char[][] board) {
        // Write your code here
        int n = board.length;
        if (n == 0) {
            return;
        }
        int m = board[0].length;

        for (int i = 0; i < n; i++) {
            bfs(board, i, 0);
            bfs(board, i, m - 1);
        }
        for (int j = 0; j < m; j++) {
            bfs(board, 0, j);
            bfs(board, n - 1, j);
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (board[i][j] == ‘W‘) {
                    board[i][j] = ‘O‘;
                } else {
                    board[i][j] = ‘X‘;
                }
            }
        }
    }

    void bfs(char[][] board, int sx, int sy) {
        if (board[sx][sy] != ‘O‘) {
            return;
        }
        int n = board.length;
        int m = board[0].length;
        int[] dx = { 0, 1, 0, -1 };
        int[] dy = { 1, 0, -1, 0 };

        Queue<Integer> qx = new LinkedList<>();
        Queue<Integer> qy = new LinkedList<>();
        qx.offer(sx);
        qy.offer(sy);
        board[sx][sy] = ‘W‘; // ‘W‘ -> Water
        while (!qx.isEmpty()) {
            int cx = qx.poll();
            int cy = qy.poll();

            for (int i = 0; i < 4; i++) {
                int nx = cx + dx[i];
                int ny = cy + dy[i];
                if (0 <= nx && nx < n && 0 <= ny && ny < m && board[nx][ny] == ‘O‘) {
                    board[nx][ny] = ‘W‘; // ‘W‘ -> Water
                    qx.offer(nx);
                    qy.offer(ny);
                }
            }
        }
    }
}

  

Surrounded Regions

标签:empty   oid   节点   script   for   一个   out   nbsp   int   

原文地址:https://www.cnblogs.com/FLAGyuri/p/12078591.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!