Surrounded Regions Codes for help


  • 0
    B

    Hi, I am a new coder and I am a little confused with my codes below, since I got "0" with the input "0" on my IDE, but I got wrong answer "X" with the OJ platform. Could anyone help me with this?

    public class Solution {
            public void solve(char[][] board) {
                if (board == null || board.length == 0) return;
                int m = board.length, n = board[0].length;
                for (int i = 0; i < m; i++) {
                    bfs(board, i, 0);
                    bfs(board, i, n-1);
                }
                for (int j = 0; j < n; j++) {
                    bfs(board, 0, j);
                    bfs(board, m-1, j);
                }
                for (int i = 0; i < m; i++) {
                    for (int j = 0; j < n; j++) {
                        if (board[i][j] == '#') board[i][j] = '0';
                        else board[i][j] = 'X';
                    }
                }
            }
            private static class Pair {
                int i;
                int j;
                public Pair(int i, int j) {
                    this.i = i;
                    this.j = j;
                }
            }
            private static int[] x = {0, 0, 1, -1};
            private static int[] y = {1, -1, 0, 0};
            // bread first search from (i,j)
            private void bfs(char[][] board, int i, int j) {
                Queue<Pair> que = new LinkedList<Pair>();
                if (!check(board, i, j)) return;
                que.add(new Pair(i, j));
                while (!que.isEmpty()) {
                    Pair p = que.poll();
                    board[p.i][p.j] = '#';
                    for (int k = 0; k < 4; k++) {
                        if (check(board, p.i + x[k], p.j + y[k])) {
                            que.add(new Pair(p.i + x[k], p.j + y[k]));
                        }
                    }
                }
            }
            private boolean check(char[][] board, int i, int j) {
                if (i >= 0 && i < board.length && j >= 0 && j < board[0].length && board[i][j] == '0') return true;
                return false;
            }
            public static void main(String[] args) {
                Solution solution = new Solution();
                char[][] board = new char[1][1];
                board[0][0] = '0';
                solution.solve(board);
                System.out.println(board[0][0]);
            }
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.