Java | O(m^2)
\n\nclass Solution {\n    public int[] executeInstructions(int n, int[] startPos, String s) {\n        int m = s.length();\n        int[] result = new int[m];\n
```\n\nclass Solution {\n    public int[] executeInstructions(int n, int[] startPos, String s) {\n        int m = s.length();\n        int[] result = new int[m];\n        for(int i = 0; i < m; i++) {\n            result[i] = (getLastInstructionPosition(n, startPos[0], startPos[1], s, i) - i);\n        }\n        return result;\n    }\n\n    private int getLastInstructionPosition(int n, int row, int col, String s, int pos) {\n        int m = s.length();\n        if(m == pos) {\n            return pos;\n        }\n        char ch = s.charAt(pos);\n        switch(ch) {\n            case \'R\' :\n                if(!isValidCell(n, row, (col + 1))) {\n                    return pos;\n                }\n                return getLastInstructionPosition(n, row, (col + 1), s, (pos + 1));\n            case \'L\' :\n                if(!isValidCell(n, row, (col - 1))) {\n                    return pos;\n                }\n                return getLastInstructionPosition(n, row, (col - 1), s, (pos + 1));\n            case \'U\' :\n                if(!isValidCell(n, (row - 1), col)) {\n                    return pos;\n                }\n                return getLastInstructionPosition(n, (row - 1), col, s, (pos + 1));\n            default :\n                if(!isValidCell(n, (row + 1), col)) {\n                    return pos;\n                }\n                return getLastInstructionPosition(n, (row + 1), col, s, (pos + 1));\n        }\n    }\n\n    private boolean isValidCell(int n, int row, int col) {\n        return (row >= 0 && row < n && col >= 0 && col < n);\n    }\n}\n\n```
[]