Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding
Ninjas X Naukri.com

Last Updated: 6 Mar, 2021

Moderate

```
The ant initially faces toward the east side. Every time an ant moves from a block, it inverts it, i.e., changes 0 to 1 and 1 to 0.
If the ant exits the matrix just return -1,-1.
```

```
If ‘N’ = 2
mat[2][2] = {{1, 1},
{0, 0}}
startingRow = 0 , startingColumn = 0
moves = 1
The ant is initially facing the east side, it will take a right turn and move 1 stop in the south.
The output will be 1 0.
```

```
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case contains four space-separated integers N, sr, and sc and moves. Where ‘N’ is the number of rows and columns in the ‘MAT’ matrix, ‘sr’ is the starting row and ‘sc’ is the starting column of the ant in the matrix, and moves are the number of moves an ant will make on the grid.
The description of the next ‘N’ lines is as follows-
Each line contains ‘N’ space-separated integers representing the elements of the matrix ‘MAT’.
```

```
For each test case, print a single line containing two space-separated integers denoting the final position of an ant[0-based indexing].
The output of each test case will be printed in a separate line.
```

```
You do not need to print anything; it has already been taken care of. Just implement the given function.
```

```
1 <= T <= 5
1 <= N <= 100
0 <= MAT[ i ][ j ] <= 1
Where ‘T’ is the total number of test cases, and 'N’ is the number of rows and columns in the ‘MAT’ matrix, and MAT[ i ][ j ] is the value of pairs (i, j).
Time limit: 1sec.
```

The idea is to use recursion and maintain a variable that tells us what direction the ant is facing. We have four different direction options up, down, left, right.

At each call, the direction we move forward will be determined by the value of the block. If the block is 0, then we take a left turn, else a right turn. Till the number of moves, we have to make after that return the final position of the ant (row, col)[0 based indexing]. If the ant ever leaves the board just return -1,-1

- Maintain a ‘DIRS’ array which tells either to move forward or backward or up or down.
- This would be determined by the direction variable that we maintained.
- If the current block is 0 then NEWDIR = CURDIR - 1.
- Else If the current block is 1 then NEWDIR = (CURDIR + 1) % 4.
- Hence move forward according to the dirs array that we maintained. The new row would be CUROW + DIRS[CURDIR], similarly, the new column will be CURCOL + DIRS[CURDIR].
- Invert the current block.

Similar problems