Problem | Find Different Path through Square Maze

Problem

Write a program to accept the number of boxes in a row of a square maze and the a set of directions to go from its northwest corner to its southeast corner (top is taken as north) containing moves to the east and south only, and display another set of directions such that for all the boxes in the second set of directions, either the box is unvisited in the first set or the direction of movement in and out of that box is different in the first set of directions. The program should first accept the number of test cases and then all the test cases, and finally display the results of all the cases.

Analysis

We can obtain a unique set of directions simply by replacing all the ‘S’ moves by ‘E’ and vice versa. This is because the total number of moves to south and east is constant for any set of directions, and by flipping ‘S’ and ‘E’, we maintain the uniqueness of the solution.

Output

Enter number of test cases.
3
Enter 3 sets of maze sizes and directions.
2
ES
5
ESEESSSE
3
SESE
Case #1: SE
Case #2: SESSEEES
Case #3: ESES

Program

/**
 * This program accepts size of a square maze and directions to solve
 * it and displays another set of unique directions.
 */
import java.io.*;
public class Maze
{
    public static String flip(String str)
    {
        str=str.replace('S','Q');
        str=str.replace('E','S');
        str=str.replace('Q','E');
        return str;
    }
    public static void main()throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter number of test cases.");
        int T=Integer.parseInt(br.readLine()),x=0;
        String ar[]=new String[T];
        System.out.println("Enter "+T+" sets of maze sizes and directions.");
        for(int i=0;i<T;i++)
        {
            x=Integer.parseInt(br.readLine());
            ar[i]=flip(br.readLine().toUpperCase());
        }
        for(int i=0;i<T;i++) 
            System.out.println("Case #"+(i+1)+": "+ar[i]);
    }
}

Leave a comment