Loading
Leetcode / 1476. Subrectangle Queries

Pick a programming language:

Here is the source code for the solution to this problem.

class SubrectangleQueries {
    private int[][] rectangle;

    public SubrectangleQueries(int[][] rectangle) {
        this.rectangle = rectangle;
    }
    
    public void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {
        int startRow;
        int endRow;
        int startCol;
        int endCol;

        // You can actually do away with these because the constraints
        // guarantee 0 <= row1 <= row2 < rows
        // and 0 <= col1 <= col2 < cols
        if (row1 < row2) {
            startRow = row1;
            endRow = row2;
        }
        else {
            startRow = row2;
            endRow = row1;
        }

        if (col1 < col2) {
            startCol = col1;
            endCol = col2;
        }
        else {
            startCol = col2;
            endCol = col1;
        }

        for (int i = startRow; i <= endRow; i++) {
            for (int j = startCol; j <= endCol; j++) {
                rectangle[i][j] = newValue;
            }
        }
    }
    
    public int getValue(int row, int col) {
        return rectangle[row][col];
    }
}

/**
 * Your SubrectangleQueries object will be instantiated and called as such:
 * SubrectangleQueries obj = new SubrectangleQueries(rectangle);
 * obj.updateSubrectangle(row1,col1,row2,col2,newValue);
 * int param_2 = obj.getValue(row,col);
 */
Did you like the lesson? 😆👍
Consider a donation to support our work: