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.

**Input:**

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**.**

**Output:**

For every test case, an output is the sum of adjacent elements according to the query.

**Constraints:**

1<=T<=50

1<=N,M<=20

1<=Q<=100

0<=i<=N

0<=j<=M

**Example:**

**Input:**

1

4 4

1 2 3 4

5 6 7 8

9 1 3 4

1 2 3 4

2

1 0 1

2 0 1

**Output:**

22

29

**Explanation:**

**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.

Author: Vanshika_pec

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.

geetyadav | 82 |

yashrana1 | 74 |

AdityaRaj9 | 73 |

abuexshaitan | 56 |

Shashi Bhushan | 52 |

abducodes | 837 |

harshtyagi36 | 399 |

sandipbhaumik | 321 |

Akhil varma | 314 |

vamsikrishna55 | 304 |

blackshadows | 5331 |

Ibrahim Nash | 5219 |

akhayrutdinov | 5111 |

mb1973 | 4929 |

Quandray | 4567 |

Login to report an issue on this page.