The input is 'O',not 'o' or '0'. Also, it's 'X', not 'x' !!!


  • 1
    I
    public class Solution {
        public void solve(char[][] board) {
            int rows = board.length;
            if (rows == 0) {
                return;
            }
            int columns = board[0].length;
            HashMap<Integer, HashSet<Integer>> ok = new HashMap<Integer, HashSet<Integer>>();
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < columns; ++j) {
                    if (i != 0 && i != rows - 1) {
                        if (j != 0 && j != columns - 1)
                            continue;
                    }
                    if ((board[i][j] == 'O') && (ok.get(i) == null || !ok.get(i).contains(j))) {
                        ArrayList<Point> tmp = new ArrayList<Point>();
                        tmp.add(new Point(i, j));
                        while (!tmp.isEmpty()) {
                            Point current = tmp.remove(0);
                            int x = current.getX(), y = current.getY();
                            if (board[x][y] == 'X' || (ok.get(x) != null && ok.get(x).contains(y)))
                                continue;
                            if (ok.get(x) == null) {
                                ok.put(x, new HashSet<Integer>());
                            }
                            ok.get(x).add(y);
                            if (x > 0)
                                tmp.add(new Point(x-1, y));
                            if (x < rows - 1)
                                tmp.add(new Point(x+1, y));
                            if (y > 0)
                                tmp.add(new Point(x, y-1));
                            if (y < columns - 1)
                                tmp.add(new Point(x, y+1));
                        }
                    }
                }
            }
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < columns; ++j) {
                    if (board[i][j] == 'O' && (ok.get(i) == null || !ok.get(i).contains(j))) {
                        board[i][j] = 'X';
                    }
                }
            }
        }
    }
    
    class Point {
        private  int x;
        private  int y;
        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    
        int getX() {
            return this.x;
        }
    
        int getY() {
            return this.y;
        }
    }

Log in to reply
 

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