|
| 1 | +package com.thealgorithms.prefixsum; |
| 2 | + |
| 3 | +/** |
| 4 | + * A class that implements the 2D Prefix Sum algorithm. |
| 5 | + * |
| 6 | + * <p>2D Prefix Sum is a technique used to preprocess a 2D matrix such that |
| 7 | + * sub-matrix sum queries can be answered in O(1) time. |
| 8 | + * The preprocessing step takes O(N*M) time. |
| 9 | + * |
| 10 | + * <p>This implementation uses a long array for the prefix sums to prevent |
| 11 | + * integer overflow. |
| 12 | + * |
| 13 | + * @see <a href="https://en.wikipedia.org/wiki/Summed-area_table">Summed-area table (Wikipedia)</a> |
| 14 | + * @author Chahat Sandhu, <a href="https://github.com/singhc7">singhc7</a> |
| 15 | + */ |
| 16 | +public class PrefixSum2D { |
| 17 | + |
| 18 | + private final long[][] prefixSums; |
| 19 | + |
| 20 | + /** |
| 21 | + * Constructor to preprocess the input matrix. |
| 22 | + * |
| 23 | + * @param matrix The input integer matrix. |
| 24 | + * @throws IllegalArgumentException if the matrix is null or empty. |
| 25 | + */ |
| 26 | + public PrefixSum2D(int[][] matrix) { |
| 27 | + if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { |
| 28 | + throw new IllegalArgumentException("Input matrix cannot be null or empty"); |
| 29 | + } |
| 30 | + |
| 31 | + int rows = matrix.length; |
| 32 | + int cols = matrix[0].length; |
| 33 | + this.prefixSums = new long[rows + 1][cols + 1]; |
| 34 | + |
| 35 | + for (int i = 0; i < rows; i++) { |
| 36 | + for (int j = 0; j < cols; j++) { |
| 37 | + // P[i+1][j+1] = current + above + left - diagonal_overlap |
| 38 | + this.prefixSums[i + 1][j + 1] = matrix[i][j] + this.prefixSums[i][j + 1] + this.prefixSums[i + 1][j] - this.prefixSums[i][j]; |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Calculates the sum of the sub-matrix defined by (row1, col1) to (row2, col2). |
| 45 | + * Indices are 0-based. |
| 46 | + * |
| 47 | + * @param row1 Top row index. |
| 48 | + * @param col1 Left column index. |
| 49 | + * @param row2 Bottom row index. |
| 50 | + * @param col2 Right column index. |
| 51 | + * @return The sum of the sub-matrix. |
| 52 | + * @throws IndexOutOfBoundsException if indices are invalid. |
| 53 | + */ |
| 54 | + public long sumRegion(int row1, int col1, int row2, int col2) { |
| 55 | + if (row1 < 0 || row2 >= prefixSums.length - 1 || row2 < row1) { |
| 56 | + throw new IndexOutOfBoundsException("Invalid row indices"); |
| 57 | + } |
| 58 | + if (col1 < 0 || col2 >= prefixSums[0].length - 1 || col2 < col1) { |
| 59 | + throw new IndexOutOfBoundsException("Invalid column indices"); |
| 60 | + } |
| 61 | + |
| 62 | + return prefixSums[row2 + 1][col2 + 1] - prefixSums[row1][col2 + 1] - prefixSums[row2 + 1][col1] + prefixSums[row1][col1]; |
| 63 | + } |
| 64 | +} |
0 commit comments