Given a square grid of size **N**, each cell of which contains integer cost which represents a cost to traverse through that cell, we need to find a path from top left cell to bottom right cell by which total cost incurred is minimum.

**Note : **It is assumed that negative cost cycles do not exist in input matrix.

**Input:**

The first line of input will contain number of testcases **T**. Then T test cases follow. Each test case contains 2 lines. The first line of each test case contains an integer N denoting the size of the grid. Next line of each test contains a single line containing N*N space separated integers depecting cost of respective cell from (0,0) to (N,N).

**Output:**

For each test case output a single integer depecting the minimum cost to reach the destination.

**Constraints:**

1 <= T <= 50

1 <= N <= 50

**Example:
Input:**

2

5

31 100 65 12 18 10 13 47 157 6 100 113 174 11 33 88 124 41 20 140 99 32 111 41 20

2

42 93 7 14

**Output**:

327

63

**Explanation:**

**Testcase 1:**

Grid is:

31, 100, 65, 12, 18,

10, 13, 47, 157, 6,

100. 113, 174, 11, 33,

88, 124, 41, 20, 140,

99, 32, 111, 41, 20

A cost grid is given in below diagram, minimum

cost to reach bottom right from top left

is 327 (31 + 10 + 13 + 47 + 65 + 12 + 18 + 6 + 33 + 11 + 20 + 41 + 20)

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.

Akkki111 | 38 |

SaltBaeSama | 34 |

ambercyrus | 33 |

LegendFire | 32 |

chocozz | 32 |

KshatriyaYash | 1932 |

nikhil_sojan | 1374 |

lonecoder | 1219 |

mazumderrohit8 | 1095 |

SumitSingh27 | 1090 |

blackshadows | 5327 |

Ibrahim Nash | 5219 |

akhayrutdinov | 5111 |

mb1973 | 4566 |

Quandray | 4444 |

Login to report an issue on this page.