Lanqiao Cup Chessboard Flip Problem (Java Implementation)

Problem Statement

We have an n×n chessbaord where every cell starts as white, represneted by the integer 0. We perform m flip operations: each operation inverts the color of all cells in a rectangular subregion bounded by rows x1 to x2 and columns y1 to y2. After completing all operation, output the final color state of each cell, with 0 indicating white and 1 indicating black.

Input Format

The first line of input contains two integers n and m, separated by a single space, representing the size of the chessboard and the total number of flip operations. Each of the next m lines contains four integers x1, y1, x2, y2 separated by spaces, which define the rectangular region to flip.

Sample Input

3 3
1 1 2 2
2 2 3 3
1 1 3 3

Output Format

Print n lines, each containing n consecutive 0 or 1 characters representing the color of each cell in that row.

Sample Output

001
010
100

Java Implementation

import java.util.Scanner;

public class ChessboardFlip {
    public static void main(String[] args) {
        try (Scanner input = new Scanner(System.in)) {
            int boardSize = input.nextInt();
            int operationCount = input.nextInt();
            int[][] chessboard = new int[boardSize][boardSize];
            
            for (int opIndex = 0; opIndex < operationCount; opIndex++) {
                int rowStart = input.nextInt();
                int colStart = input.nextInt();
                int rowEnd = input.nextInt();
                int colEnd = input.nextInt();
                flipRectangularRegion(chessboard, rowStart, colStart, rowEnd, colEnd);
            }
            
            for (int row = 0; row < boardSize; row++) {
                StringBuilder rowBuffer = new StringBuilder();
                for (int col = 0; col < boardSize; col++) {
                    rowBuffer.append(chessboard[row][col]);
                }
                System.out.println(rowBuffer);
            }
        }
    }
    
    private static void flipRectangularRegion(int[][] board, int r1, int c1, int r2, int c2) {
        int startRow = r1 - 1;
        int endRow = r2 - 1;
        int startCol = c1 - 1;
        int endCol = c2 - 1;
        
        for (int currentRow = startRow; currentRow <= endRow; currentRow++) {
            for (int currentCol = startCol; currentCol <= endCol; currentCol++) {
                board[currentRow][currentCol] = 1 - board[currentRow][currentCol];
            }
        }
    }
}

Tags: Lanqiao Cup java Chessboard Problem 2D Array Flip Algorithm Competition

Posted on Fri, 21 Aug 2026 16:15:55 +0000 by psymonic