Rat in a Maze Backtracking Problem

https://practice.geeksforgeeks.org/problems/rat-in-a-maze-problem/1#

Please check out above link and tell me why cases are getting failed even it is running in my intellij Idea
My solution is given below:

class Solution {
static ArrayList res = new ArrayList<>();
public static ArrayList findPath(int[][] m, int n) {
// Your code here
mazePath(m, 0, 0, “”);
return res;
}

public static void mazePath(int[][] m, int row, int col, String ans) {
    if(row < 0 || col < 0 || row >= m.length || col >= m[0].length || m[row][col] == 0) {
        return;
    }
    if(row == m.length-1 && col == m.length-1) {
        res.add(ans);
        return;
    }
    
    m[row][col] = 0;
    // U
    mazePath(m, row-1, col, ans + "U");
    // R
    mazePath(m, row, col+1, ans + "R");
    // D
    mazePath(m, row+1, col, ans + "D");
    // L
    mazePath(m, row, col-1, ans + "L");
    m[row][col] = 1;
}

}

Hey @danishrehman288 You are getting duplicate answers bcoz you have initiated the ArrayList globally which means everytime a function is called changes will be made but previous element which are already present in arraylist will also be there(means wrong answers). I have changed your code : (Changes are made in the array list initialization and first line of findpath method.) the concept is I will reinitialize the array list everytime to prevent storage of prev answers.

class Solution {
    static ArrayList<String> res;
    public static ArrayList<String> findPath(int[][] m, int n) {
        // Your code here
        res = new ArrayList<>();
        mazePath(m, 0, 0, "");
      return res;
    }
    public static void mazePath(int[][] m, int row, int col, String ans) {
    if(row < 0 || col < 0 || row >= m.length || col >= m[0].length || m[row][col] == 0) {
        return;
    }
    if(row == m.length-1 && col == m.length-1) {
        res.add(ans);
        return;
    }
    
    m[row][col] = 0;
    // U
    mazePath(m, row-1, col, ans + "U");
    // R
    mazePath(m, row, col+1, ans + "R");
    // D
    mazePath(m, row+1, col, ans + "D");
    // L
    mazePath(m, row, col-1, ans + "L");
    m[row][col] = 1;
}
}

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.