The Postmaster has asked the postman's to write a program to answer the queries regarding letter collection in a city. A city is represented as a matrix of size N X M. Each cell represents a house and contains letters which are denoted by a number in the 2D array. The Postmaster ask Q queries which need to be answered, which are of following types:
1 i j : To sum all the letters which are just at a 1-hop distance from the cell (i,j) in any direction i.e moving 1 step from a cell(i,j) to a cell it shares a common edge with.
2 i j : To sum all the letters which are at a 2-hop distance from the cell (i,j) in any direction i.e moving 2 step from a cell(i,j) to a cell it shares a common edge with.
The first line of input contains integer T denoting the number of test cases. Each test case has subsequent two lines of input. The first line contains 2 integer inputs i.e N and M the size of the matrix W.Next line contains the N X M space separated elements of the matrix W i.e the number of letters. Next line contains the a integer Q denoting the number of queries. Next Q lines input the query in 1 i j or 2 i j form where i, j are the index of the element in the 2d array.
For every test case, an output is the sum of adjacent elements according to the query.
1 2 3 4
5 6 7 8
9 1 3 4
1 2 3 4
1 0 1
2 0 1
1. By 1 0 1 , it means 1 hop distance around element at (0,1) i.e 2. Therefore adding elements at (0,0),(0,2),(1,0),(1,1)(1,2) i.e. 1+3+5+6+7=22.
2. By 2 0 1, it means 2 hop distance around element at (0,1). Hence adding elements at (2,0),(2,1),(2,2),(2,3),(1,3),(0,3) i.e. 9+1+3+4+8+4=29.
If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.