A Short C# BFS Solution -- 158ms


  • 0
    L
    public void Solve(char[,] board) {
        Queue<int[]> queue = new Queue<int[]>();
        int width = board.GetLength(1), height = board.GetLength(0);
        for(int i = 0; i < height; i++)
            for(int j = 0; j < width; j++)
                if((i == 0 || i == height - 1 || j == 0 || j == width - 1) && board[i, j] == 'O')
                    queue.Enqueue(new int[]{i, j});
        while(queue.Count != 0){
            int i = queue.Peek()[0], j = queue.Dequeue()[1];
            if(board[i, j] != 'O') continue;
            board[i, j] = 'T';
            if(i > 0 && board[i - 1, j] == 'O') queue.Enqueue(new int[]{i - 1, j});
            if(i < height - 1 && board[i + 1, j] == 'O') queue.Enqueue(new int[]{i + 1, j});
            if(j > 0 && board[i, j - 1] == 'O') queue.Enqueue(new int[]{i, j - 1});
            if(j < width - 1 && board[i, j + 1] == 'O') queue.Enqueue(new int[]{i, j + 1});
        }
        for(int i = 0; i < height; i++)
            for(int j = 0; j < width; j++)
                board[i, j] = board[i, j] == 'O' ? 'X' : board[i, j] == 'T' ? 'O' : 'X';
    }

Log in to reply
 

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