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

130. Surrounded Regions

时间:2017-07-23 22:55:37      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:数组   region   logs   log   oid   ons   boolean   cti   blog   

Given a 2D board containing X and O (the letter O), capture all regions surrounded by X.

A region is captured by flipping all Os into Xs 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

矩阵的bfs, 套路一致,从外向内, 很easy

构造类, 遍历矩阵建立图

bfs要点在于如何建图, 是否建类, 建比较器, 建方向容器, 建走过的路的存储器(数组, 或者set, list) 如何遍历(堆不空?), 遍历到内部的点时判断是否符合题意(边界, 走过), 再考虑题意, 判断当前的点是否符合题意来加入结果的容器 或结果值, 将当前的点加入堆中是否要改变值啊什么的, 关键在于建立的是什么图. 里面的点是怎么个意思, 都是题意的转化

class Cell {
    int x, y;
    public Cell(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
public class Solution {
   
    public void solve(char[][] board) {
        if(board == null || board.length == 0 || board[0].length == 0) return;
        int m = board.length;
        int n = board[0].length;
        Queue<Cell> q = new LinkedList<>();
        int[][] directions = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        boolean [][] visited = new boolean[m][n];
        for (int j=0; j<board[0].length; j++) {
            if (board[0][j] == ‘O‘) q.offer(new Cell(0, j));
            if (board[board.length-1][j] == ‘O‘) q.offer(new Cell(board.length-1, j));
            visited[0][j] = true;
            visited[m - 1][j] =  true;
        }
        for (int i=0; i<board.length; i++) {
            if (board[i][0] == ‘O‘) q.offer(new Cell(i, 0));
            if (board[i][board[0].length-1] == ‘O‘) q.offer(new Cell(i, board[0].length-1));
            visited[i][0] = true;
            visited[i][n - 1] =  true;
        }
        while (!q.isEmpty()) {
            Cell cur = q.poll();
            board[cur.x][cur.y] = ‘$‘;
            
            for (int[] dir : directions) {
                int x = dir[0] + cur.x;
                int y = dir[1] + cur.y;
                if (x < 0 || y < 0 || x >= m || y >= n || visited[x][y] || board[x][y] == ‘X‘) {
                    continue;
                }
                visited[x][y] = true;
                q.offer(new Cell(x, y));
            }
        }
        for (int i=0; i<board.length; i++) {
            for (int j=0; j<board[0].length; j++) {
                if (board[i][j] == ‘X‘) continue;
                else if (board[i][j] == ‘$‘) board[i][j] = ‘O‘;
                else if (board[i][j] == ‘O‘) board[i][j] = ‘X‘;
            }
        }
    }
}

  

130. Surrounded Regions

标签:数组   region   logs   log   oid   ons   boolean   cti   blog   

原文地址:http://www.cnblogs.com/apanda009/p/7226100.html

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