Straightforward iterative solution (316ms)


  • 0
    A
    public class Solution {
        public void solve(char[][] board) {
            boolean change = true;
            while (change) {
                change = false;
                for (int i = 0; i < board.length; i++) {
                    for (int j = 0; j < board[i].length; j++) {
                        if (board[i][j] == 'O') {
                            if (i == 0 || i == board.length - 1 ||
                                j == 0 || j == board[i].length - 1 ||
                                board[i-1][j] == '1' || board[i+1][j] == '1' ||
                                board[i][j-1] == '1' || board[i][j+1] == '1') {
                                board[i][j] = '1';
                                change = true;
                            }
                        }
                    }
                }
            }
            
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[i].length; j++) {
                    if (board[i][j] == '1') board[i][j] = 'O';
                    else if (board[i][j] == 'O') board[i][j] = 'X';
                }
            }
            
        }
    }

Log in to reply
 

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