Open In App

Postmaster Letters Collection

Last Updated : 08 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Postmaster wants to write a program to answer the queries regarding letter collection in a city. A city is represented as a matrix mat[][] of size n*m. Each cell represents a house and contains letters that are denoted by a number in the cell. The program should answer q queries where queries[i][0] will represent query type, query[i][1] and query[i][2] will represent i and j values respectively which are of the following types:

  1. (i, j) : To sum all the letters which are at a 1-hop distance from the cell (i,j) in any direction
  2. (i, j) : To sum all the letters which are at a 2-hop distance from the cell (i,j) in any direction

The queries are given in a 2D matrix queries[][].
In one hop distance postmaster can go to any of [(i-1,j-1), (i-1,j), (i-1,j+1), (i,j-1), (i,j+1), (i+1,j-1), (i+1,j), (i+1,j+1)] from (i,j).

Example:

Input: n = 4, m = 5, q = 2, queries = {{1 0 1}, {2 0 1}}
mat = {{1, 2, 3, 4, 10},
  {5, 6, 7, 8, 10},
  {9, 1, 3, 4, 10},
  {1, 2, 3, 4, 10}}
Output: 22 29
Explanation: For the first query sum is 1+5+6+7+3 = 22.
For the second query sum is 9+1+3+4+8+4 = 29.

Input: n = 6, m = 6, q = 1, queries = {{2 3 2}}
mat = {{ 1, 2, 3, 4, 5, 6},
{ 7, 8, 9, 10, 11, 12},
{13, 14, 15, 16, 17, 18},
{19, 20, 21, 22, 23, 24},
{25, 26, 27, 28, 29, 30},
{31, 32, 33, 34, 35, 36}}
Output: 336
Explanation: The first query sum is 7+8+9+10+11+17+23+29+35+34+33+32+31+25+19+13 = 336.

Approach:

In this, we will do as told in the question we will find the sum of values for every query, and for each, we will add only those index values that are valid(i.e. not out of bound).

  • Initialize variables sum equal to 0 and il, jl, ir, and jr to represent the indices for every query.
  • Initialize a vector result to store the answer.
  • Run a loop i from 0 to q.
    • update sum equal to 0, and update the variable il equals to (queries[i][1] – queries[i][0]), jl equals to (queries[i][2] – queries[i][0]), ir equals to (queries[i][1] + queries[i][0]), jr equal to (queries[i][2] + queries[i][0]).
    • Run a loop i from il to ir.
      • If the row i and column jl is valid then add the values at ith row and jlth column from the matrix mat into the sum.
      • If the row i and column jr is valid then add the values at ith row and jrth column from the matrix mat into the sum.
    • Run a loop i from jl+1 to jr.
      • If the row il and column i is valid then add the values at ilth row and ith column from the matrix mat into the sum.
      • If the row ir and column i is valid then add the values at irth row and ith column from the matrix mat into the sum.
    • Push the value of sum into the result array.
  • Return the result array.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to check if given indices are valid within the
// matrix
bool valid(int i, int j, int n, int m)
{
    if (i >= 0 && j >= 0 && i < n && j < m)
        return true;
    return false;
}
 
// Function to calculate the sum of elements within the
// specified queries
vector<int> matrixSum(int n, int m,
                      vector<vector<int> > mat, int q,
                      vector<int> queries[])
{
    int sum = 0, il, jl, ir, jr;
    vector<int> result;
 
    // Loop over each query
    for (int i = 0; i < q; i++) {
        sum = 0;
 
        // Calculate the indices for the top-left and the
        // bottom-right corners of the submatrix
        il = queries[i][1] - queries[i][0];
        jl = queries[i][2] - queries[i][0];
        ir = queries[i][1] + queries[i][0];
        jr = queries[i][2] + queries[i][0];
 
        // Iterate over the rows of the submatrix
        for (int i = il; i <= ir; i++) {
            // Check if the current index is valid, and if
            // so, add the corresponding element to the sum
            if (valid(i, jl, n, m))
                sum += mat[i][jl];
            if (valid(i, jr, n, m))
                sum += mat[i][jr];
        }
 
        // Iterate over the columns of the submatrix
        for (int i = jl + 1; i < jr; i++) {
            // Check if the current index is valid, and if
            // so, add the corresponding element to the sum
            if (valid(il, i, n, m))
                sum += mat[il][i];
            if (valid(ir, i, n, m))
                sum += mat[ir][i];
        }
 
        // Store the sum for the current query in the result
        // vector
        result.push_back(sum);
    }
 
    // Return the vector containing the sums for all queries
    return result;
}
 
int main()
{
 
    int n = 4; // Number of rows
    int m = 5; // Number of columns
 
    vector<vector<int> > mat = { { 1, 2, 3, 4, 10 },
                                 { 5, 6, 7, 8, 10 },
                                 { 9, 1, 3, 4, 10 },
                                 { 1, 2, 3, 4, 10 } };
 
    int q = 2; // Number of queries
 
    vector<int> queries[q];
    queries[0] = { 1, 0, 1 };
    queries[1] = { 2, 0, 1 };
 
    vector<int> result = matrixSum(n, m, mat, q, queries);
 
    for (int i = 0; i < q; i++) {
        cout << "Sum for Query " << i + 1 << ": "
             << result[i] << endl;
    }
 
    return 0;
}


Java




import java.util.*;
 
public class MatrixSum {
 
    // Function to check if given indices are valid within
    // the matrix
    static boolean valid(int i, int j, int n, int m)
    {
        return i >= 0 && j >= 0 && i < n && j < m;
    }
 
    // Function to calculate the sum of elements within the
    // specified queries
    static List<Integer> matrixSum(int n, int m,
                                   List<List<Integer> > mat,
                                   int q, int[][] queries)
    {
        int sum, il, jl, ir, jr;
        List<Integer> result = new ArrayList<>();
 
        // Loop over each query
        for (int i = 0; i < q; i++) {
            sum = 0;
 
            // Calculate the indices for the top-left and
            // the bottom-right corners of the submatrix
            il = queries[i][1] - queries[i][0];
            jl = queries[i][2] - queries[i][0];
            ir = queries[i][1] + queries[i][0];
            jr = queries[i][2] + queries[i][0];
 
            // Iterate over the rows of the submatrix
            for (int j = il; j <= ir; j++) {
                // Check if the current index is valid, and
                // if so, add the corresponding element to
                // the sum
                if (valid(j, jl, n, m))
                    sum += mat.get(j).get(jl);
                if (valid(j, jr, n, m))
                    sum += mat.get(j).get(jr);
            }
 
            // Iterate over the columns of the submatrix
            for (int j = jl + 1; j < jr; j++) {
                // Check if the current index is valid, and
                // if so, add the corresponding element to
                // the sum
                if (valid(il, j, n, m))
                    sum += mat.get(il).get(j);
                if (valid(ir, j, n, m))
                    sum += mat.get(ir).get(j);
            }
 
            // Store the sum for the current query in the
            // result vector
            result.add(sum);
        }
 
        // Return the list containing the sums for all
        // queries
        return result;
    }
 
    public static void main(String[] args)
    {
        int n = 4; // Number of rows
        int m = 5; // Number of columns
 
        List<List<Integer> > mat
            = Arrays.asList(Arrays.asList(1, 2, 3, 4, 10),
                            Arrays.asList(5, 6, 7, 8, 10),
                            Arrays.asList(9, 1, 3, 4, 10),
                            Arrays.asList(1, 2, 3, 4, 10));
 
        int q = 2; // Number of queries
 
        int[][] queries = { { 1, 0, 1 }, { 2, 0, 1 } };
 
        List<Integer> result
            = matrixSum(n, m, mat, q, queries);
 
        for (int i = 0; i < q; i++) {
            System.out.println("Sum for Query " + (i + 1)
                               + ": " + result.get(i));
        }
    }
}


Python




# Python code to implement the above approach
 
# Function to check if given indices are valid
# within the matrix
 
 
def valid(i, j, n, m):
    return 0 <= i < n and 0 <= j < m
 
# Function to calculate the sum of elements
# within the specified queries
 
 
def matrix_sum(n, m, mat, q, queries):
    result = []
 
    # Loop over each query
    for query in queries:
        sum = 0
 
        # Calculate the indices for the top-left and
        # the bottom-right corners of the submatrix
        il = query[1] - query[0]
        jl = query[2] - query[0]
        ir = query[1] + query[0]
        jr = query[2] + query[0]
 
        # Iterate over the rows of the submatrix
        for i in range(il, ir + 1):
            # Check if the current index is valid, and if
            # so, add the corresponding element to the sum
            if valid(i, jl, n, m):
                sum += mat[i][jl]
            if valid(i, jr, n, m):
                sum += mat[i][jr]
 
        # Iterate over the columns of the submatrix
        for i in range(jl + 1, jr):
            # Check if the current index is valid, and if
            # so, add the corresponding element to the sum
            if valid(il, i, n, m):
                sum += mat[il][i]
            if valid(ir, i, n, m):
                sum += mat[ir][i]
 
        # Store the sum for the current query in
        # the result array
        result.append(sum)
 
    # Return the list containing the sums for all queries
    return result
 
# Driver code
 
 
def main():
    n = 4  # Number of rows
    m = 5  # Number of columns
 
    mat = [
        [1, 2, 3, 4, 10],
        [5, 6, 7, 8, 10],
        [9, 1, 3, 4, 10],
        [1, 2, 3, 4, 10]
    ]
 
    q = 2  # Number of queries
 
    queries = [
        [1, 0, 1],
        [2, 0, 1]
    ]
 
    result = matrix_sum(n, m, mat, q, queries)
 
    for i, res in enumerate(result):
        print("Sum for Query {}: {}".format(i + 1, res))
 
 
if __name__ == "__main__":
    main()
 
# This code is contributed by Abhinav Mahajan (abhinav_m22).


C#




using System;
using System.Collections.Generic;
 
class GFG
{
    static bool Valid(int i, int j, int n, int m)
    {
        return i >= 0 && j >= 0 && i < n && j < m;
    }
    // Function to calculate the sum of the elements within the specified queries
    static List<int> MatrixSum(int n, int m, List<List<int>> mat, int q, List<int[]> queries)
    {
        List<int> result = new List<int>();
        // Loop over each query
        for (int queryIndex = 0; queryIndex < q; queryIndex++)
        {
            int sum = 0;
            // Calculate the indices for the top-left and
          // the bottom-right corners of the submatrix
            int il = queries[queryIndex][1] - queries[queryIndex][0];
            int jl = queries[queryIndex][2] - queries[queryIndex][0];
            int ir = queries[queryIndex][1] + queries[queryIndex][0];
            int jr = queries[queryIndex][2] + queries[queryIndex][0];
            // Iterate over the rows of the submatrix
            for (int i = il; i <= ir; i++)
            {
                // Check if the current index is valid and if so
              // add the corresponding element to the sum
                if (Valid(i, jl, n, m))
                    sum += mat[i][jl];
                if (Valid(i, jr, n, m))
                    sum += mat[i][jr];
            }
            // Iterate over the columns of the submatrix
            for (int j = jl + 1; j < jr; j++)
            {
                // Check if the current index is valid, and if so
              // add the corresponding element to the sum
                if (Valid(il, j, n, m))
                    sum += mat[il][j];
                if (Valid(ir, j, n, m))
                    sum += mat[ir][j];
            }
            // Store the sum for the current query in result list
            result.Add(sum);
        }
        // Return the list containing
      // the sums for all queries
        return result;
    }
    static void Main()
    {
        int n = 4; // Number of rows
        int m = 5; // Number of columns
        List<List<int>> mat = new List<List<int>> {
            new List<int> {1, 2, 3, 4, 10},
            new List<int> {5, 6, 7, 8, 10},
            new List<int> {9, 1, 3, 4, 10},
            new List<int> {1, 2, 3, 4, 10}
        };
        int q = 2; // Number of queries
        List<int[]> queries = new List<int[]> {
            new int[] {1, 0, 1},
            new int[] {2, 0, 1}
        };
        List<int> result = MatrixSum(n, m, mat, q, queries);
        for (int i = 0; i < q; i++)
        {
            Console.WriteLine($"Sum for Query {i + 1}: {result[i]}");
        }
    }
}


Javascript




// Javascript code for the above approach
 
// Function to check if given indices are valid
// within the matrix
function valid(i, j, n, m)
{
    if (i >= 0 && j >= 0 && i < n && j < m)
        return true;
    return false;
}
 
// Function to calculate the sum of elements
// within the specified queries
function matrixSum(n, m, mat, q, queries)
{
    let sum = 0, il, jl, ir, jr;
    let result = [];
 
    // Loop over each query
    for (let i = 0; i < q; i++) {
        sum = 0;
 
        // Calculate the indices for the top-left and
        // the bottom-right corners of the submatrix
        il = queries[i][1] - queries[i][0];
        jl = queries[i][2] - queries[i][0];
        ir = queries[i][1] + queries[i][0];
        jr = queries[i][2] + queries[i][0];
 
        // Iterate over the rows of the submatrix
        for (let i = il; i <= ir; i++) {
            // Check if the current index is valid, and if
            // so, add the corresponding element to the sum
            if (valid(i, jl, n, m))
                sum += mat[i][jl];
            if (valid(i, jr, n, m))
                sum += mat[i][jr];
        }
 
        // Iterate over the columns of the submatrix
        for (let i = jl + 1; i < jr; i++) {
            // Check if the current index is valid, and if
            // so, add the corresponding element to the sum
            if (valid(il, i, n, m))
                sum += mat[il][i];
            if (valid(ir, i, n, m))
                sum += mat[ir][i];
        }
 
        // Store the sum for the current query in
        // the result array
        result.push(sum);
    }
 
    // Return the array containing the sums for all queries
    return result;
}
 
// Driver code
function main()
{
    let n = 4; // Number of rows
    let m = 5; // Number of columns
 
    let mat = [[ 1, 2, 3, 4, 10 ],
                [ 5, 6, 7, 8, 10 ],
                [ 9, 1, 3, 4, 10 ],
                [1, 2, 3, 4, 10 ]];
 
    let q = 2; // Number of queries
 
    let queries = new Array(q);
    queries[0] = [ 1, 0, 1 ];
    queries[1] = [ 2, 0, 1 ];
 
    let result = matrixSum(n, m, mat, q, queries);
 
    for (let i = 0; i < q; i++) {
        console.log("Sum for Query ", i + 1,  ": ",
                        result[i]);
    }
}
 
main()
 
// This code is contributed by ragul21


Output

Sum for Query 1: 22
Sum for Query 2: 29











Time Complexity: O(q*(n+m))
Auxiliary Space: O(q)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads