Count the steps before visiting cell repeated

Viewed 37

Description

Given a 2d array with 'U', 'D', 'L', 'R' representing up, down, left, right => count the number of steps you have taken before reaching an already visited cell or going outside the 2d array.

Note: The first step is always taken to cell located at (0,0).

Input The first line of the input contains T, the number of test cases.

The first line of each test case contains N, and M, the number of rows, and columns in the 2D Array.

The next lines of the test case, contains M characters each, denoting the values in the 2D array.

Constraints

1 <= T <= 10

1 <= N,M <= 100

Output Print a single integer, denoting the number of steps, you take before stepping out of the 2D array, or visiting an already visited cell, on a new line.

Sample Input 1

1 3 4 RRDR LLUD LLLL Sample Output 1

4 Hint

1 Answers

Something like this. You can first enter the path and check if the path starts from a specific sign like "X". if not then implement conditions for individual signs such as "R", "L", "U" & "D", in every step replace these symbols with the specific sign "X" and count all individual paths taken, If case you find the sign "X" then return the count.

function Path(string){
    count = 0;
    i = 0;
    j = 0;
    while(i >= 0 && j >= 0 && i < string.length && j < string.length){
            if (string[i][j] === 'X'){
                count=0;
                // return 0;
                break;
            } 
            if (string[i][j] === 'L'){
                string[i][j] = 'X';
                j--;
            }
            else if (string[i][j] === 'R'){
                string[i][j] = 'X';
                j++;
            }
            else if (string[i][j] == 'U'){
                string[i][j] = 'X';
                i--;
            }
            else{
                string[i][j] = 'X';
                i++;
            }
            count++;
    }
    return count;
        
}

Related