There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1). You are given the integer n and an integer array startPos where startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol).
You are also given a 0-indexed string s of length m where s[i] is the ith instruction for the robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down).
The robot can begin executing from any ith instruction in s. It executes the instructions one by one towards the end of s but it stops if either of these conditions is met:
The next instruction will move the robot off the grid.
There are no more instructions left to execute.
Return an arrayanswerof lengthmwhereanswer[i]is the number of instructions the robot can execute if the robot begins executing from theithinstruction ins.
Example 1:
Input: n = 3, startPos = [0,1], s = "RRDDLU"
Output: [1,5,4,3,1,0]
Explanation: Starting from startPos and beginning execution from the ith instruction:
- 0th: "RRDDLU". Only one instruction "R" can be executed before it moves off the grid.
- 1st: "RDDLU". All five instructions can be executed while it stays in the grid and ends at (1, 1).
- 2nd: "DDLU". All four instructions can be executed while it stays in the grid and ends at (1, 0).
- 3rd: "DLU". All three instructions can be executed while it stays in the grid and ends at (0, 0).
- 4th: "LU". Only one instruction "L" can be executed before it moves off the grid.
- 5th: "U". If moving up, it would move off the grid.
Input: n = 1, startPos = [0,0], s = "LRUD"
Output: [0,0,0,0]
Explanation: No matter which instruction the robot begins execution from, it would move off the grid.
/** * Note: The returned array must be malloced, assume caller calls free(). */int*executeInstructions(intn,int*startPos,intstartPosSize,char*s,int*returnSize){intm=strlen(s);int*ans=malloc(sizeof(int)*m);for(inti=0;i<m;i++){inty=startPos[0];intx=startPos[1];intj=i;for(j=i;j<m;j++){if(s[j]=='U'){y--;}elseif(s[j]=='D'){y++;}elseif(s[j]=='L'){x--;}else{x++;}if(y==-1||y==n||x==-1||x==n){break;}}ans[i]=j-i;}*returnSize=m;returnans;}