Associated Course(s):
Must Do Interview Preparation

Given a boolean 2D matrix (0-based index), find whether there is path from (0,0) to (x,y) and if there is one path, print the minimum no of steps needed to reach it, else print -1 if the destination is not reachable. You may move in only four direction ie up, down, left and right. The path can only be created out of a cell if its value is 1.

**Input:**

The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains two lines . The first line of each test case contains two integers n and m denoting the size of the matrix. Then in the next line are n*m space separated values of the matrix. The following line after it contains two integers x and y denoting the index of the destination.

**Output:**

For each test case print in a new line the min no of steps needed to reach the destination.

**Constraints:**

1<=T<=100

1<=n,m<=20

**Example:
Input:**

2

3 4

1 0 0 0 1 1 0 1 0 1 1 1

2 3

3 4

1 1 1 1 0 0 0 1 0 0 0 1

0 3

5

3

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.

hardikJain5 | 110 |

CodeBuddy | 107 |

Akkki111 | 100 |

saurabhgrade1 | 98 |

WrongAnswer | 80 |

KshatriyaYash | 1932 |

nikhil_sojan | 1374 |

lonecoder | 1236 |

SumitSingh27 | 1103 |

mazumderrohit8 | 1095 |

blackshadows | 5327 |

Ibrahim Nash | 5219 |

akhayrutdinov | 5111 |

mb1973 | 4566 |

Quandray | 4444 |

Login to report an issue on this page.