In the game of Broken Blocks, the player is allowed to move on M x N blocks i.e. M levels and N stone blocks on each level such that one level is vertically above the previous level (as in a staircase), with some of its stone blocks replaced by wooden blocks. The player at the start of the game is present on the ground level (which should be considered as level ‘0’ or it can be considered as level ‘-1’). The player can start from any of the blocks present on the level ‘0^{’} and start moving further to next levels. The player can only move to the stone-block just above to the present stone-block or diagonally to the left or to the right. The player can’t move on the same level. If the player steps on any of the wooden block (denoted by -1), he will fall off the board and die as the wood-block will not able to hold player’s weight. Each of the stone-block has some gold coins present on it (wooden blocks doesn’t have any coins on them). If at any point the player can’t move to further level due to any reason, the game ends and his present total coin score will be considered. The player’s aim is to collect as many gold coins as he can without falling off the board (What’s the use of money if you don’t have a life?).

**Input:**

The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case contains two integers M and N denoting the size of the matrix. The next line contains M x N elements. Each element of the matrix denotes the number of coins present on the block at the position of the element. Wooden blocks are denoted by -1.

**Output:**

For each test case, print in a new line the maximum number of coins the player can collect.

**Constraints:**

1 <= T <= 1000

2 <= M, N <= 100

-1 <= a[M][N] <= 10^6

**Example:**

**Input:**

2

3 3

2 5 6 -1 3 2 4 -1 5

3 4

-1 2 3 4 5 -1 -1 2 4 3 -1 1

**Output:**

14

11

**Explanation:**

Assume 0-based indexing.

The matrix for the **1 ^{st} test case** is:

2 5 6 (level 0)

-1 3 2 (level 1)

4 -1 5 (lever 2)

The player can collect maximum number of coins by moving through:

a[0][2] + a[1][1] + a[2][2] = 6 + 3 + 5 = 14 coins.

The matrix for the **2 ^{nd} test case** is:

-1 2 3 4

5 -1 -1 2

4 3 -1 1

The player can collect maximum number of coins by moving through:

a[0][1] + a[1][0] + a[2][0] = 2 + 5 + 4 = 11 coins.

Author: sajalagrawal

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.

d_Coder00 | 134 |

Astikeysingh | 128 |

dungeon_master1299 | 126 |

rajendrashekhawat063 | 115 |

VivSisMMM | 112 |

Pulkit__Sharma__ | 646 |

Anirban166 | 531 |

abducodes | 508 |

Found_me | 474 |

Sathvik Avasarala | 418 |

blackshadows | 5331 |

Ibrahim Nash | 5219 |

akhayrutdinov | 5111 |

mb1973 | 4929 |

Quandray | 4559 |

Login to report an issue on this page.