Postmaster Letters Collection
Last Updated :
08 Dec, 2023
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:
- (i, j) : To sum all the letters which are at a 1-hop distance from the cell (i,j) in any direction
- (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;
bool valid( int i, int j, int n, int m)
{
if (i >= 0 && j >= 0 && i < n && j < m)
return true ;
return false ;
}
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;
for ( int i = 0; i < q; i++) {
sum = 0;
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];
for ( int i = il; i <= ir; i++) {
if (valid(i, jl, n, m))
sum += mat[i][jl];
if (valid(i, jr, n, m))
sum += mat[i][jr];
}
for ( int i = jl + 1; i < jr; i++) {
if (valid(il, i, n, m))
sum += mat[il][i];
if (valid(ir, i, n, m))
sum += mat[ir][i];
}
result.push_back(sum);
}
return result;
}
int main()
{
int n = 4;
int m = 5;
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;
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 {
static boolean valid( int i, int j, int n, int m)
{
return i >= 0 && j >= 0 && i < n && j < m;
}
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<>();
for ( int i = 0 ; i < q; i++) {
sum = 0 ;
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 ];
for ( int j = il; j <= ir; j++) {
if (valid(j, jl, n, m))
sum += mat.get(j).get(jl);
if (valid(j, jr, n, m))
sum += mat.get(j).get(jr);
}
for ( int j = jl + 1 ; j < jr; j++) {
if (valid(il, j, n, m))
sum += mat.get(il).get(j);
if (valid(ir, j, n, m))
sum += mat.get(ir).get(j);
}
result.add(sum);
}
return result;
}
public static void main(String[] args)
{
int n = 4 ;
int m = 5 ;
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 ;
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
def valid(i, j, n, m):
return 0 < = i < n and 0 < = j < m
def matrix_sum(n, m, mat, q, queries):
result = []
for query in queries:
sum = 0
il = query[ 1 ] - query[ 0 ]
jl = query[ 2 ] - query[ 0 ]
ir = query[ 1 ] + query[ 0 ]
jr = query[ 2 ] + query[ 0 ]
for i in range (il, ir + 1 ):
if valid(i, jl, n, m):
sum + = mat[i][jl]
if valid(i, jr, n, m):
sum + = mat[i][jr]
for i in range (jl + 1 , jr):
if valid(il, i, n, m):
sum + = mat[il][i]
if valid(ir, i, n, m):
sum + = mat[ir][i]
result.append( sum )
return result
def main():
n = 4
m = 5
mat = [
[ 1 , 2 , 3 , 4 , 10 ],
[ 5 , 6 , 7 , 8 , 10 ],
[ 9 , 1 , 3 , 4 , 10 ],
[ 1 , 2 , 3 , 4 , 10 ]
]
q = 2
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()
|
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;
}
static List< int > MatrixSum( int n, int m, List<List< int >> mat, int q, List< int []> queries)
{
List< int > result = new List< int >();
for ( int queryIndex = 0; queryIndex < q; queryIndex++)
{
int sum = 0;
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];
for ( int i = il; i <= ir; i++)
{
if (Valid(i, jl, n, m))
sum += mat[i][jl];
if (Valid(i, jr, n, m))
sum += mat[i][jr];
}
for ( int j = jl + 1; j < jr; j++)
{
if (Valid(il, j, n, m))
sum += mat[il][j];
if (Valid(ir, j, n, m))
sum += mat[ir][j];
}
result.Add(sum);
}
return result;
}
static void Main()
{
int n = 4;
int m = 5;
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;
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
function valid(i, j, n, m)
{
if (i >= 0 && j >= 0 && i < n && j < m)
return true ;
return false ;
}
function matrixSum(n, m, mat, q, queries)
{
let sum = 0, il, jl, ir, jr;
let result = [];
for (let i = 0; i < q; i++) {
sum = 0;
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];
for (let i = il; i <= ir; i++) {
if (valid(i, jl, n, m))
sum += mat[i][jl];
if (valid(i, jr, n, m))
sum += mat[i][jr];
}
for (let i = jl + 1; i < jr; i++) {
if (valid(il, i, n, m))
sum += mat[il][i];
if (valid(ir, i, n, m))
sum += mat[ir][i];
}
result.push(sum);
}
return result;
}
function main()
{
let n = 4;
let m = 5;
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;
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()
|
Output
Sum for Query 1: 22
Sum for Query 2: 29
Time Complexity: O(q*(n+m))
Auxiliary Space: O(q)
Share your thoughts in the comments
Please Login to comment...