AlgoUniversity
  • Go Back
Discussion
Minimum Rolls :

Author

Shikhar Mehrotra

Difficulty Level : Medium

Submissions : 278

Asked In : Appdynamics

Marks :50

: 2 | : 1

You are given a grid of dimension $$$N$$$ * $$$M$$$, where each cell has a number $$$0$$$ or $$$1$$$ on it.$$$0$$$ represents a wall which means you cannot pass through it, and $$$1$$$ means you are free to move. Find the minimum number of rolls required to reach from given source cell to destination cell or report "-1", but condition on rolling is that if you roll , then it continues to roll in the same direction until it gets an edge of grid , or the cell is blocked i.e cell has $$$0$$$ on it.

You can either move right(R), left(L), up(U) or down(D)

Input

The first line contains two space-separated integers $$$1\le N \le 1000$$$ $$$1\le M \le 1000$$$.

Following N lines contains M space separated integers which are either $$$0$$$ or $$$1$$$.

The next line contains two space-separated integers $$$1\le source_{x} \le N$$$ $$$1\le source_{y} \le M$$$

The next line contains two space-separated integers $$$1\le destination_{x} \le N$$$ $$$1\le destination_{y} \le M$$$

Output

Output minimum rolls if possible else output "-1".

Examples

Input
5 5
1 1 1 0 0
0 0 1 0 0
0 1 1 1 1
0 1 0 1 1
0 1 1 1 1
1 1
5 5
Output
8
Input
5 5
1 1 1 1 1
0 0 1 1 0
0 1 1 1 1
0 1 0 1 1 
0 1 1 1 1
1 1
5 5
Output
-1

Note

In first test case you have to roll from $$$(1,1)$$$ to $$$(5,5)$$$.

You can move like this $$$RRDDRRDD$$$ for moving from source to target in minimum rolls.

As you can see here after completing $$$4_{th}$$$ roll you have two direction either go $$$L$$$ or $$$R$$$, but chosing $$$R$$$ gives minimum rolls.

You need to login to view your submissions.

You need to login to view all submissions.

Loading...

Result : Executed

Loading...

Feel something is wrong with the test cases?

Result : Accepted

Test Cases :

You need to Log In
We're glad that you want to attempt this problem!

But to Run or Submit the Problem, you need to Log In.

Continue to Log In
Challenge Submitted!

Your challenge has been submitted successfully.

You will get a response soon via WhatsApp or Email.

Challenge
Facing issue while trying to solve the problem! Don't worry, we got you covered!

Do let us know your issue.

Looks good!
Please enter your issue / feedback.

How do we get in touch with you?
Looks good!
Please enter your phone no.
Looks good!
Please enter your email address.