Given a n*n matrix, find the maximum length path (starting from any cell) such that all cells along the path are in increasing order with a difference of 1.

We can move in 4 directions from a given cell (i, j), i.e., we can move to (i+1, j) or (i, j+1) or (i-1, j) or (i, j-1) with the condition that the adjacent cells have a difference of 1.

**Input:**

The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer n denoting the size of the nxn matrix. The following lines contain the nxn matrix.

**Output:**

Print the length of the longest path.

**Constraints:**

1<=T<=100

1<=n<=50

1<=arr[i][j]<=50

**Example:
Input:**

2

3

1 2 9 5 3 8 4 6 7

4

1 7 8 9 2 11 12 17 3 15 14 13 4 5 25 30

**Output:**

4

5

Author: Ayush Govil 1

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.

ShubhamJain18 | 205 |

makeitdonesolo | 140 |

lost_found | 124 |

maggiiiii | 118 |

SahatPrasad1 | 108 |

Bishnu Dev Panda | 777 |

okayboss | 551 |

ShubhamJain18 | 516 |

yk12 | 514 |

makeitdonesolo | 480 |

blackshadows | 5331 |

Ibrahim Nash | 5219 |

akhayrutdinov | 5111 |

mb1973 | 4925 |

Quandray | 4547 |

Login to report an issue on this page.