Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Help with solving Maze

  1. #1
    Junior Member
    Join Date
    May 2012
    Posts
    5
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Help with solving Maze

    Hi there. So I'm supposed to make a program that solve a given maze with "m"(mouse) indicated the starting point, "c" (cheese)indicated the exit, "-" = traversable and "w" == wall. I can't think of a way to use my visited() method, i.e preventing the mouse from visiting the same space over and over (all base cases such as hit wall or index out of bound are handled with my traversable()). Any help would be greatly appreciated
    Here is the input file (in .txt format)
    4
    5
    ---ww
    wwm-w
    c-w--
    w---w

    Here is the Driver. There is nothing wrong with it (I believe as it just calls the methods in the Maze class)
    package a07;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.util.InputMismatchException;
    import java.util.Scanner;
    import java.util.logging.Level;
    import java.util.logging.Logger;
     
    /**
     *
     * @author Tim
     */
    public class A07 {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            /*
             * Getting the file name from user's input...
             */
            Scanner fileName = new Scanner(System.in);
            System.out.println("Please enter the file name...");
            String name = fileName.nextLine();
     
            try {
                Scanner scanInput = new Scanner(new FileReader(name)); //reading the file in a try-catch
                while (scanInput.hasNextLine()) { //checking for the file validity
                    try {  //reading the first 2 ints in a try-catch. If this block fails, break the loop                             
                            //and return invalid file
                        int row = scanInput.nextInt(); //scanning for the number of rows
                        scanInput.nextLine();
     
                        int column = scanInput.nextInt(); //scanning for the number of columns
                        scanInput.nextLine();
     
                        int actualRow = 0; 
                        boolean correctCol = true; //setting the boolean of checkCol to true
                        while (scanInput.hasNextLine()) { //checking row
                            if (scanInput.next().length() != column) { //during checking row, check column. 
                                correctCol = false;//if ONE column fails, change the correctCol boolean to false
                            }
     
                            actualRow+=1;
     
                            if (scanInput.hasNextLine()) {
                                scanInput.nextLine(); 
                            }
                        }
                        if (actualRow != row) { //comparing number of row by user AND the number of row we got from checking the input
                            System.out.println("Invalid maze row input!");//if they don't match --> error
                            break;
                        }
     
                        else if (actualRow == row) {//if they DO match,check if column inputs matches
                            if (correctCol == true) { //if they do, move one to the next step
                                //System.out.println("success! Your maze input is correct !");
                                Scanner scanMaze = new Scanner(new FileReader(name));
                                scanMaze.nextLine();//these 2 lines move the cursor
                                scanMaze.nextLine();//past the first 2 ints
                                                    //to get to the actual maze inputs
     
                                String[][] maze = new String[row][column]; //assigning the maze to the dimension indicated by 
                                                                    //the inputs from the user
     
     
     
                                String[] mazeLines = new String[row];//create a String array of length *row* to store
                                                                    //each lines of the maze input
     
                                /*********************************************
                                 * the 2 lines below store each maze input****
                                 * lines into the array created above.********
                                *///******************************************
                                for (int i = 0; i < mazeLines.length; i++) {
                                    mazeLines[i] = scanMaze.nextLine();
                                }
                                /*******************************************************
                                 * READ THE COMMENTS OF THIS CODE BLOCK CAREFULLY AND*** 
                                 * TRY TO UNDERSTAND IT. THIS IS THE KEY BLOCK OF THIS**
                                 * METHOD !!! LET ME KNOW IF YOU HAVE ANY QUESTION !!!**
                                 *///***************************************************
                                for (int i = 0; i < mazeLines.length;i++) {  //this code block pull each line of the mazeLines***************
                                    for (int j = 0;j < column;j++) {//array, then pick out a character at the index j and convert************            
                                        char mazeChar = mazeLines[i].charAt(j);//it to a string character. Then, it will assigne that string*        
                                        String mazeStr = Character.toString(mazeChar);//value to the matrix maze at position maze[i][j]******    
                                        maze[i][j] = mazeStr;
                                    }
                                }
                                //ASSIGNING THE MATRIX CREATED WITH THE INPUTS TO THE 
                                //MAZE.**********************************************
     
                                Maze myMaze = new Maze(maze);
                                myMaze.maze = maze;
                                myMaze.solver();
                                System.out.println(myMaze.getMouse());
     
     
     
     
     
                            }
                            else {//if they don't, print out error message
                                System.out.println("Your actual maze input does not"
                                        + " match your indicated dimension!");
                            }
                        }
     
                        break;
     
                    } catch(InputMismatchException e) { //catch mismatch input, returning invalidFile()
                        System.out.println("Wrong input!");
                        break;
                    }
                }
     
            } catch (FileNotFoundException ex) {
                System.out.println("Invalid file input !");
            }
     
     
     
     
        }
    }

    Here is the Maze class. This is where all my methods take place. This is the one causing the problems.
    package a07;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.util.ArrayList;
    import java.util.InputMismatchException;
    import java.util.Scanner;
     
    /**
     *
     * @author Tim
     */
    public class Maze {
        protected String[][] maze;
        protected ArrayList<String> solutions;
     
        public Maze(String[][] maze) {
            this.maze = maze;
        }
     
        public Point getPos(String a) { //getting the coordinates of any given string
           for (int i = 0; i < this.maze.length; i++) {//in the maze. i is the number
               for (int j = 0; j < this.maze[0].length; j++) {//of row, j is the number
                   if ((this.maze[i][j]).equals(a)) {           //of column
                       Point pos = new Point(i,j);
                       return pos;
                   }
               }
           }
           return null;
       }
     
       public Point getMouse() { //returning the coordinates of the mouse.
           return getPos("m");
       }
     
       public String invalidFile() { //returning error when fail in reading the input
           return "No maze found !";
       }
     
     
     
       //the traversable method checks whether the mouse can go to a point.
       //For a point (x,y), if either x or y is < 0, or if x > the number of row
       //of y > than the number of column, the Point is not traversable.
       public boolean traversable(int row, int col) { 
           if (row < 0 || col < 0 || row > this.maze.length - 1 || col > this.maze[0].length - 1
                   || this.maze[row][col].equals("w")) {
               return false;
           }
     
           else {
               return true;
           }
     
     
       }
     
       //This method checks for whether 
       //the mouse moved to a specific 
       //slot already or not.
       public boolean visited(int row, int col) {
           while (row > 0 && row <= this.maze.length && col > 0 && col <= this.maze[0].length) {
               if (this.maze[row][col].equals("x")) {
               return true;
           }
     
           }
           return false;
     
     
       }
       /*MOUSE*************
        *TRAVERSE**********
        *///METHODS********
       //before a move is made, each method checks for whether the mouse can move
       //there or not. If it can, it will change the coordinate of the new position
       //to "m" (mouse), and set the mouse's previous position to "x".
       public void moveDown(){
           Point mouse = this.getMouse();
           int oldRow = mouse.getRow();
           int oldCol = mouse.getCol();
     
           int newRow = oldRow + 1;
           int newCol = oldCol;
            System.out.println(this.traversable(newRow, newCol));
           if (this.traversable(newRow, newCol)) {
               this.maze[newRow][newCol] = "m";
               this.maze[oldRow][oldCol] = "x";
               System.out.println("down");
               System.out.println("mouse at: " + this.getMouse());
           }
           else if (this.traversable(newRow, newCol) == false) {
               this.moveLeft();
           }
       }
     
       public void moveUp() {
           Point mouse = this.getMouse();
           int oldRow = mouse.getRow();
           int oldCol = mouse.getCol();
     
           int newRow = oldRow - 1;
           int newCol = oldCol;
            System.out.println(this.traversable(newRow, newCol));
           if (this.traversable(newRow, newCol)) {
               this.maze[newRow][newCol] = "m";
               this.maze[oldRow][oldCol] = "x";
               System.out.println("up");
               System.out.println("mouse at: " + this.getMouse());
           }
           else if (this.traversable(newRow, newCol) == false) {
               this.moveDown();
           }
     
       }
     
       public void moveLeft() {
           Point mouse = this.getMouse();
           int oldRow = mouse.getRow();
           int oldCol = mouse.getCol();
     
           int newRow = oldRow;
           int newCol = oldCol - 1;
           System.out.println(this.traversable(newRow, newCol));
     
           if (this.traversable(newRow, newCol)) {
               this.maze[newRow][newCol] = "m";
               this.maze[oldRow][oldCol] = "x";
               System.out.println("left");
               System.out.println("mouse at: " + this.getMouse());
     
           }
           else if (this.traversable(newRow, newCol) == false) {
               this.moveRight();
           }
     
       }
     
       public void moveRight() {
           Point mouse = this.getMouse();
           int oldRow = mouse.getRow();
           int oldCol = mouse.getCol();
     
           int newRow = oldRow;
           int newCol = oldCol + 1;
            System.out.println(this.traversable(newRow, newCol));
           if (this.traversable(newRow, newCol)) {
               this.maze[newRow][newCol] = "m";
               this.maze[oldRow][oldCol] = "x";
               System.out.println("right"); 
               System.out.println("mouse at: " + this.getMouse());
           }
           else if (this.traversable(newRow, newCol) == false) {
               this.moveUp();
           }
     
       }
       //This is the base case
     
       public boolean baseCase() {
           Point mouse = this.getMouse();
           int mouseRow = mouse.getRow();
           int mouseCol = mouse.getCol();
     
           Point cheese = this.getPos("c");
           int chRow = cheese.getRow();
           int chCol = cheese.getCol();
     
           if (mouseRow == chRow && mouseCol == chCol ) {
               return true;
           }
     
           else {
               return false;
           }
       }
       //this is the method used to solve the maze.
       public void solver() {
           Point currentMouse = this.getMouse();
           if (this.baseCase()) {
               System.out.println("CHEESE!");
           }
           else {
               this.moveDown();
               this.solver();
           }

    This is the support Point class that gets coordinates for any given string in a Maze.
    package a07;
     
    /**
     *
     * @author Tim
     */
    public class Point {
        protected int row;
        protected int col;
     
        public Point(int row, int col ) {
            this.row = row;
            this.col = col;
        }
     
        public int getRow() {
            return row;
        }
        public void setRow(int row) {
            this.row = row;
        }
     
        public int getCol() {
            return col;
        }
        public void setCol(int col) {
            this.col = col;
        }
     
        @Override
        public String toString() {
            return "Row: " + row + " " + "Column: " + col;
        }
    }
    Last edited by tcao2; May 5th, 2012 at 09:25 AM.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with solving Maze

    Why does the code read the file two times?

    Can you explain your search algorithm?

    A suggestion for testing: define the maze in a String:
            String theMaze = "4\n5\n---ww\nwwm-w\nc-w--\nw---w\n";  // have the maze here
     
            try {
                Scanner scanInput = new Scanner(theMaze); //new FileReader(name)); //reading the file in a try-catch


    Also your debug print out do not have enough info. add some more. For example:

    System.out.println("mR trav=" + traversable(newRow, newCol) + " row="+newRow + " col=" + newCol);


    Another debugging hint.
    Add a counter to stop recurive calls looping forever:
       int maxLoopCnt  = 0; // stop forever search  <<<<<<<<<<<<<<<<
     
       //this is the method used to solve the maze.
       public void solver() {
          if(maxLoopCnt++ > 50)  return; //   <<<<<<<<<<<<<<< stop looping
    Last edited by Norm; May 5th, 2012 at 11:38 AM.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    tcao2 (May 5th, 2012)

  4. #3
    Junior Member
    Join Date
    May 2012
    Posts
    5
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Help with solving Maze

    Well the first time it reads the file to make sure that the input is correct. The input format is supposed to be an int for row, then an int for column, then the maze. The first scan is to make sure that the input is correct and the number of rows and columns correspond to the actual maze dimension. The second scan will get the actual maze, break it down into char, convert the chars back into Strings, then assign them into the 2D String[][] array.

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with solving Maze

    Seems like it could be done in one pass.

    Can you explain your search algorithm?
    If you don't understand my answer, don't ignore it, ask a question.

  6. #5
    Junior Member
    Join Date
    May 2012
    Posts
    5
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Help with solving Maze

    OK so I made the traversable() method to check if a move can be made or not. If it is out of bound, return false. If it hits the wall, return false. Otherwise, return true and move. If it moves down, then change the mouse current location to "-", and change maze[currentRow + 1][currentColumn] to "m". If it can't move down, then call moveRight(), if it can't move right, then call moveLeft()...then back to moveDown() recursively till a solution is found. I'm having trouble figuring out a way to prevent the mouse from moving to the same spot twice, since it would just move up, down, left, right in a square right now with my current methods. Thanks for your reply.

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with solving Maze

    I don't think your explanation of the logic is correct.
    I don't see where you change the location to "-"
    I do see where you change a location to an "x"

    Your explanation uses code and not words. For example what is this code doing:
    change maze[currentRow + 1][currentColumn]
    If you don't understand my answer, don't ignore it, ask a question.

  8. The Following User Says Thank You to Norm For This Useful Post:

    tcao2 (May 5th, 2012)

  9. #7
    Junior Member
    Join Date
    May 2012
    Posts
    5
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Help with solving Maze

    Quote Originally Posted by Norm View Post
    I don't think your explanation of the logic is correct.
    I don't see where you change the location to "-"
    I do see where you change a location to an "x"

    Your explanation uses code and not words. For example what is this code doing:
    change maze[currentRow + 1][currentColumn]
    Hi there again, thank you for your replies. I've been working on it and the program is almost completed. I'm trying to get it to print out that path that it takes and this is the final part I'm struggling with.
    So as a maze is solved, the path it takes from the mouse original position to the cheese will be marked with "1". I took advantage of this to back track the path that the mouse took. From the mouse starting position, I will check its left, right, up and down alternatively and look for the string "1". If "1" is found to the left of the mouse, I will move the mouse there (change that "1" to "m"), change the mouse's previous position to a "0", then print out "left". From there, do those steps again and print out the appropriate directions (left, right, up or down) until the mouse's position is the same as the Cheese's. I accomplished this with my code and most of the time it works, but for some cases it just seems to get into an infinite loop. Any help or hint would be greatly appreciate ! The method that I'm talking about is the last method of the class below.

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package a07;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.util.ArrayList;
    import java.util.InputMismatchException;
    import java.util.Scanner;
     
    /**
     *
     * @author Tim
     */
    public class Maze {
        protected String[][] maze;
        protected ArrayList<String> solutions;
        protected int chRow=0,chCol=0,totCounter=0,nosolCounter=0;//globally declared cheese row and column
        protected String[][] solvedMaze;
        protected String[][] copy;
     
        public Maze(String[][] maze) {//constructor
    		solutions = new ArrayList<String>();
            this.maze = maze;
    		Point cheese = this.getPos("c");//sarches for the cheese in the given maze
    		chRow = cheese.getRow();//gets the row and columns for the cheese
    		chCol = cheese.getCol();
    //		System.out.println("i found the cheese");
    		maze[chRow][chCol]="-";//chenages the thing that was cheese to a moveable space
    //		System.out.println("and now i changed it");
                    copy = new String[this.maze.length][this.maze[0].length];
                    for (int i = 0; i < this.maze.length; i++) {
                        for (int j = 0; j < this.maze[0].length; j++) {
                            copy[i][j] = this.maze[i][j];
                        }
                    }
        }
     
    	public String getPath(){
    		this.path();
    		String path="";
    		System.out.println("number of solution steps: " + solutions.size());
    		for (int i=0;i<solutions.size(); i++) {
    			path = this.solutions.get(i);
    		}
    		return path;
    	}
     
        public Point getPos(String a) { //the same as before
           for (int i = 0; i < this.maze.length; i++) {
               for (int j = 0; j < this.maze[0].length; j++) {
                   if ((this.maze[i][j]).equals(a)) {
                       Point pos = new Point(i,j);
                       return pos;
                   }
               }
           }
           return null;
       }
     
       public Point start() {
           for (int i = 0; i < this.copy.length; i++) {
               for (int j = 0; j < this.copy[0].length; j++) {
                   if (this.copy[i][j].equals("m")) {
                       Point begin = new Point(i,j);
                       return begin;
                   }
               }
           }
           return null; 
       }
     
     
       public Point getMouse() {// the same as before
           return getPos("m");
       }
     
       public String invalidFile() {
           return "No maze found !";
       }
     
    	public boolean solExist(){
    		if (totCounter>nosolCounter) {
    			return true;
    		}
    		return false;
    	}
     
       public boolean traversable(int row, int col, String pos) { //gets x,y, and comparator string
           while (row >= 0 && col >= 0 && row <= this.maze.length - 1 && col <= this.maze[0].length - 1) {
               if (maze[row][col].equals(pos)) {//this helps with the priority system
    		   return true;
    	   }
               else {
                   return false;
               }
           }
     
           return false;//default
       }
     
       public void moveDown(String check,String placement){//gets 2 strings, first to send to travesable, the second to replace visited spot
           Point mouse = this.getMouse();
           int oldRow = mouse.getRow();
           int oldCol = mouse.getCol();
     
           int newRow = oldRow + 1;
           int newCol = oldCol;
     
           if (this.traversable(newRow, newCol,check)) {
    		   this.maze[newRow][newCol] = "m";
    		   this.maze[oldRow][oldCol] = placement;//this get rid of the need to have a visited method
    //		   System.out.println("down");
    //		   System.out.println("mouse at: " + this.getMouse());//your statements
           }
       }
     
    	public void moveUp(String check,String placement) {
           Point mouse = this.getMouse();
           int oldRow = mouse.getRow();
           int oldCol = mouse.getCol();
     
           int newRow = oldRow - 1;
           int newCol = oldCol;
     
           if (this.traversable(newRow, newCol,check)) {
    		   this.maze[newRow][newCol] = "m";
    		   this.maze[oldRow][oldCol] = placement;
    //		   System.out.println("up");
    //		   System.out.println("mouse at: " + this.getMouse());
           }
       }
     
       public void moveLeft(String check,String placement) {
           Point mouse = this.getMouse();
           int oldRow = mouse.getRow();
           int oldCol = mouse.getCol();
     
           int newRow = oldRow;
           int newCol = oldCol - 1;
     
           if (this.traversable(newRow, newCol,check)) {
    		   this.maze[newRow][newCol] = "m";
    		   this.maze[oldRow][oldCol] = placement;
    //		   System.out.println("left");
    //		   System.out.println("mouse at: " + this.getMouse());
           } 
       }
     
       public void moveRight(String check,String placement) {
           Point mouse = this.getMouse();
           int oldRow = mouse.getRow();
           int oldCol = mouse.getCol();
     
           int newRow = oldRow;
           int newCol = oldCol + 1;
     
           if (this.traversable(newRow, newCol,check)) {
    		   this.maze[newRow][newCol] = "m";
    		   this.maze[oldRow][oldCol] = placement;
    //		   System.out.println("right");
    //		   System.out.println("mouse at: " + this.getMouse());
           }
       }
     
       public boolean baseCase() {
           Point mouse = this.getMouse();
           int mouseRow = mouse.getRow();
           int mouseCol = mouse.getCol();
     
           if (mouseRow == chRow && mouseCol == chCol){//separate lines of if statements i though this might help, it didnt
               return true;
           }
    	   return false;
       }
     
    	public String[][] getSolvedMaze(){
    		return solvedMaze;
    	}
       public void solver() {
    	   Point mouse = this.getMouse();
    	   int mouseRow = mouse.getRow();//gets mouse position
    	   int mouseCol = mouse.getCol();
           if (baseCase() == true) {
    //         System.out.println("CHEESE!");
               this.solvedMaze = new String[this.maze.length][this.maze[0].length];
               for (int i = 0; i < this.solvedMaze.length; i++) {
                   for (int j = 0; j < this.solvedMaze[0].length; j++) {
                       this.solvedMaze[i][j] = this.maze[i][j];
                   }
               }
     
               totCounter++;
           }
           else if (baseCase() == false) {
    		   //up
    //		   System.out.println("checking up0");//checks if movement is valid this is the priority system
    			if (traversable(mouseRow-1,mouseCol,"-")){//using traversable to check
    //				System.out.println("checked up0");
    				moveUp("-","1");//actuall moves on the maze
    				solver();//calls itself again
    			}
    		   //down
    //		   System.out.println("checking down0");//we still need to surround these in try catch blocks to prevent exceptions
    			if (traversable(mouseRow+1,mouseCol,"-")){
    //				System.out.println("checked down0");
    				moveDown("-","1");
    				solver();
    			}
    		   //left
    //		   System.out.println("checking left0");
    			if (traversable(mouseRow,mouseCol-1,"-")){
    //				System.out.println("checked left0");
    				moveLeft("-","1");
    				solver();
    			}
    		   //right
    //		   System.out.println("checking right0");
    			if (traversable(mouseRow,mouseCol+1,"-")){
    //				System.out.println("checked right0");
    				moveRight("-","1");
    				solver();
    			}
    		   //up1
    //		   System.out.println("checking up1");//if no places are open start checking at visited spots
    		   if (traversable(mouseRow-1,mouseCol,"1")){
    //			   System.out.println("checked up1");
    			   moveUp("1","2");
    			   solver();
    		   }
    		   //down1
    //		   System.out.println("checking down1");
    		   if (traversable(mouseRow+1,mouseCol,"1")){
    //			   System.out.println("checked down1");
    			   moveDown("1","2");
    			   solver();
    		   }
    		   //left1
    //		   System.out.println("checking left1");
    		   if (traversable(mouseRow,mouseCol-1,"1")){
    //			   System.out.println("checked left1");
    			   moveLeft("1","2");
    			   solver();
    		   }
    		   //right1
    //		   System.out.println("checking right1");
    		   if (traversable(mouseRow,mouseCol+1,"1")){
    //			   System.out.println("checked right1");
    			   moveRight("1","2");
    			   solver();
    		   }
    		   // if none are true then there are no solutions
    			if ((traversable(mouseRow-1,mouseCol,"1"))==false && (traversable(mouseRow+1,mouseCol,"1"))==false && (traversable(mouseRow,mouseCol-1,"1"))==false && (traversable(mouseRow,mouseCol+1,"1"))==false) {
    //				System.out.println("no solutions found");
    				totCounter++;
    				nosolCounter++;
    			}
           }
       }
     
     
       //adding solutions to solutions list. //THIS IS THE METHOD THAT PRINTS OUT THE PATHS THE MOUSE TOOK
       public void path() {
           int startRow = this.start().getRow();
           int startCol = this.start().getCol();
           this.solvedMaze[startRow][startCol] = "m";
           while ((startCol != chCol || startRow != chRow)) {
    		   //System.out.println("am i in");
     
            if ((startRow+1) >= 0 && startCol >= 0 && (startRow+1) <= this.maze.length - 1
                    && startCol <= this.maze[0].length - 1){
               if (this.solvedMaze[startRow + 1][startCol].equals("1")) {
                   this.solutions.add("down");
                   this.solvedMaze[startRow][startCol] = "0";
                   this.solvedMaze[startRow + 1][startCol] = "m";
                   System.out.println("down");
                   startRow=startRow+1;
               }
     
               else if (startRow + 1 == chRow && startCol == chCol) {
                   System.out.println("down");
                   this.solutions.add("down");
                   break;
               }
            }
     
             if ((startRow-1) >= 0 && startCol >= 0 && (startRow-1) <= this.maze.length - 1 && startCol <= this.maze[0].length - 1){
               if (this.solvedMaze[startRow - 1][startCol].equals("1")) {
                   this.solutions.add("up");
                   this.solvedMaze[startRow][startCol] = "0";
                   this.solvedMaze[startRow - 1][startCol] = "m";
                   System.out.println("up");
                   startRow=startRow-1;
               }
               else if (startRow - 1 == chRow && startCol == chCol) {
                   this.solutions.add("up");
                   System.out.println("up");
                   break;
     
               }
             }
     
             if (startRow >= 0 && (startCol+1) >= 0 && startRow <= this.maze.length - 1 && (startCol+1) <= this.maze[0].length - 1){
               if (this.solvedMaze[startRow][startCol + 1].equals("1")) {
                   this.solutions.add("right");
                   this.solvedMaze[startRow][startCol] = "0";
                   this.solvedMaze[startRow][startCol + 1] = "m";
                   System.out.println("right");
                   startCol=startCol+1;
               }
     
               else if (startRow == chRow && startCol + 1 == chCol) {
                   System.err.println("right");
                   this.solutions.add("right");
                   break;
               }
             }
     
            if (startRow >= 0 && (startCol-1) >= 0 && startRow <= this.maze.length - 1 && (startCol-1) <= this.maze[0].length - 1){
               if (this.solvedMaze[startRow][startCol - 1].equals("1")) {
                   this.solutions.add("left");
                   this.solvedMaze[startRow][startCol] = "0";
                   this.solvedMaze[startRow][startCol - 1] = "m";
                   System.out.println("left");
                   startCol=startCol-1;
               }
     
               else if (startRow == chRow && startCol == chCol) {
                   System.out.println("left");
                   this.solutions.add("left");
                   break;
               }
     
            }
           }
           this.solutions.add("CHEESE!");
       }
    }

  10. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with solving Maze

    Another suggestion:
    Instead of hardcoding "1" all over the program, define a String variable with a meaningful name and use that variable in the code to make it more readable and to allow the compiler to help you. If you mistakenly coded "12" or "2" some where, the code would compile but not work correctly.
    Also a meaningful name makes the code more readable.

    final String OldPosition = "1"; // use to mark the mouse's old position.

    The posted code does not have a main method. How do you execute it for testing?
    If you don't understand my answer, don't ignore it, ask a question.

  11. #9
    Junior Member
    Join Date
    May 2012
    Posts
    5
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Help with solving Maze

    Quote Originally Posted by Norm View Post
    Another suggestion:
    Instead of hardcoding "1" all over the program, define a String variable with a meaningful name and use that variable in the code to make it more readable and to allow the compiler to help you. If you mistakenly coded "12" or "2" some where, the code would compile but not work correctly.
    Also a meaningful name makes the code more readable.

    final String OldPosition = "1"; // use to mark the mouse's old position.

    The posted code does not have a main method. How do you execute it for testing?
    Sorry. Here is the Driver and the support Point class.
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package a07;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.util.InputMismatchException;
    import java.util.Scanner;
    import java.util.logging.Level;
    import java.util.logging.Logger;
     
    /**
     *
     * @author Tim
     */
    public class A07 {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            /*
             * Getting the file name from user's input...
             */
            Scanner fileName = new Scanner(System.in);
            System.out.println("Please enter the file name...");
            String name = fileName.nextLine();
     
            try {
                Scanner scanInput = new Scanner(new FileReader(name)); //reading the file in a try-catch
                while (scanInput.hasNextLine()) { //checking for the file validity
                    try {  //reading the first 2 ints in a try-catch. If this block fails, break the loop                             
                            //and return invalid file
                        int row = scanInput.nextInt(); //scanning for the number of rows
                        scanInput.nextLine();
     
                        int column = scanInput.nextInt(); //scanning for the number of columns
                        scanInput.nextLine();
     
                        int actualRow = 0; 
                        boolean correctCol = true; //setting the boolean of checkCol to true
                        while (scanInput.hasNextLine()) { //checking row
                            if (scanInput.next().length() != column) { //during checking row, check column. 
                                correctCol = false;//if ONE column fails, change the correctCol boolean to false
                            }
     
                            actualRow+=1;
     
                            if (scanInput.hasNextLine()) {
                                scanInput.nextLine(); 
                            }
                        }
                        if (actualRow != row) { //comparing number of row by user AND the number of row we got from checking the input
                            System.out.println("Invalid maze row input!");//if they don't match --> error
                            break;
                        }
     
                        else if (actualRow == row) {//if they DO match,check if column inputs matches
                            if (correctCol == true) { //if they do, move one to the next step
                                //System.out.println("success! Your maze input is correct !");
                                Scanner scanMaze = new Scanner(new FileReader(name));
                                scanMaze.nextLine();//these 2 lines move the cursor
                                scanMaze.nextLine();//past the first 2 ints
                                                    //to get to the actual maze inputs
     
                                String[][] maze = new String[row][column]; //assigning the maze to the dimension indicated by 
                                                                    //the inputs from the user
     
     
     
                                String[] mazeLines = new String[row];//create a String array of length *row* to store
                                                                    //each lines of the maze input
     
                                /*********************************************
                                 * the 2 lines below store each maze input****
                                 * lines into the array created above.********
                                *///******************************************
                                for (int i = 0; i < mazeLines.length; i++) {
                                    mazeLines[i] = scanMaze.nextLine();
                                }
                                /*******************************************************
                                 * READ THE COMMENTS OF THIS CODE BLOCK CAREFULLY AND*** 
                                 * TRY TO UNDERSTAND IT. THIS IS THE KEY BLOCK OF THIS**
                                 * METHOD !!! LET ME KNOW IF YOU HAVE ANY QUESTION !!!**
                                 *///***************************************************
                                for (int i = 0; i < mazeLines.length;i++) {  //this code block pull each line of the mazeLines***************
                                    for (int j = 0;j < column;j++) {//array, then pick out a character at the index j and convert************            
                                        char mazeChar = mazeLines[i].charAt(j);//it to a string character. Then, it will assigne that string*        
                                        String mazeStr = Character.toString(mazeChar);//value to the matrix maze at position maze[i][j]******    
                                        maze[i][j] = mazeStr;
                                    }
                                }
                                //ASSIGNING THE MATRIX CREATED WITH THE INPUTS TO THE 
                                //MAZE.**********************************************
     
                                Maze myMaze = new Maze(maze);
                                myMaze.maze = maze;
    							myMaze.solver();
    							if (myMaze.solExist()==true) {
    								System.out.println("a solution was found");
    								//System.out.println(myMaze.getPath());
     
    							}
    							else {
    								System.out.println("no solutions were found");
    							}
     
     
     
     
                            }
                            else {//if they don't, print out error message
                                System.out.println("Your actual maze input does not"
                                        + " match your indicated dimension!");
                            }
                        }
     
                        break;
     
                    } catch(InputMismatchException e) { //catch mismatch input, returning invalidFile()
                        System.out.println("Wrong input!");
                        break;
                    }
                }
     
            } catch (FileNotFoundException ex) {
                System.out.println("Invalid file input !");
            }
     
     
     
     
        }
    }

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package a07;
     
    /**
     *
     * @author Tim
     */
    public class Point {
        protected int row;
        protected int col;
     
        public Point(int row, int col ) {
            this.row = row;
            this.col = col;
        }
     
        public int getRow() {
            return row;
        }
        public void setRow(int row) {
            this.row = row;
        }
     
        public int getCol() {
            return col;
        }
        public void setCol(int col) {
            this.col = col;
        }
     
        @Override
        public String toString() {
            return "Row: " + row + " " + "Column: " + col;
        }
    }

    Here is the test case:
    4
    5
    ---ww
    wwm-w
    c-w-w
    w---w

  12. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with solving Maze

    For testing the logic of solver() I'd hardcode a maze in the program and not use the huge read and verify code.
    Your debug print out could use a lot more data. printing left,right etc doesn't say enough. Here's what my print out looks like:

    M @ Row: 0 Column: 0 cheese @ Row: 2 Column: 0
    [m, -, -, w, w]
    [w, w, -, -, w]
    [c, -, w, -, -]
    [w, -, -, -, w]
    mD trav=false row=1 col=0
    mL trav=false row=0 col=-1
    mR trav=true row=0 col=1
    setVisited contents before=m after set row=0, col=0 sqr=x
    right mouse at: Row: 0 Column: 1
    mD trav=false row=1 col=1
    mL trav=true row=0 col=0
    setVisited contents before=m after set row=0, col=1 sqr=x
    left mouse at: Row: 0 Column: 0
    mD trav=false row=1 col=0
    mL trav=false row=0 col=-1
    mR trav=true row=0 col=1
    setVisited contents before=M after set row=0, col=0 sqr=y
    right mouse at: Row: 0 Column: 1
    mD trav=false row=1 col=1
    mL trav=false row=0 col=0
    mR trav=true row=0 col=2
    setVisited contents before=M after set row=0, col=1 sqr=y
    right mouse at: Row: 0 Column: 2
    mD trav=true row=1 col=2
    setVisited contents before=m after set row=0, col=2 sqr=x
    down mouse at: Row: 1 Column: 2
    mD trav=false row=2 col=2
    mL trav=false row=1 col=1
    mR trav=true row=1 col=3
    setVisited contents before=m after set row=1, col=2 sqr=x
    right mouse at: Row: 1 Column: 3
    mD trav=true row=2 col=3
    setVisited contents before=m after set row=1, col=3 sqr=x
    down mouse at: Row: 2 Column: 3
    mD trav=true row=3 col=3
    setVisited contents before=m after set row=2, col=3 sqr=x
    down mouse at: Row: 3 Column: 3
    mD trav=false row=4 col=3
    mL trav=true row=3 col=2
    setVisited contents before=m after set row=3, col=3 sqr=x
    left mouse at: Row: 3 Column: 2
    mD trav=false row=4 col=2
    mL trav=true row=3 col=1
    setVisited contents before=m after set row=3, col=2 sqr=x
    left mouse at: Row: 3 Column: 1
    mD trav=false row=4 col=1
    mL trav=false row=3 col=0
    mR trav=true row=3 col=2
    setVisited contents before=m after set row=3, col=1 sqr=x
    right mouse at: Row: 3 Column: 2
    mD trav=false row=4 col=2
    mL trav=true row=3 col=1
    setVisited contents before=M after set row=3, col=2 sqr=y
    left mouse at: Row: 3 Column: 1
    mD trav=false row=4 col=1
    mL trav=false row=3 col=0
    mR trav=false row=3 col=2
    mU trav=true row=2 col=1
    setVisited contents before=M after set row=3, col=1 sqr=y
    up mouse at: Row: 2 Column: 1
    mD trav=false row=3 col=1
    mL trav=true row=2 col=0
    setVisited contents before=m after set row=2, col=1 sqr=x
    left mouse at: Row: 2 Column: 0
    CHEESE!
    M @ Row: 2 Column: 0 count=15
    [y, y, x, w, w]
    [w, w, x, x, w]
    [m, x, w, x, -]
    [w, y, y, x, w]
    I used these String definitions to mark squares in the maze:
        //---------------------------------------------------------
        final String Wall = "w";
        final String Empty = "-";
        final String Mouse= "m";
        final String MouseBT = "M";        // show mouse backtracking over an x
        final String VisitedOnce = "x";
        final String VisitedTwice = "y";  // when back tracking so we know this way is deadend
        final String Cheese = "c";

    Done for tonight. Back tomorrow.
    If you don't understand my answer, don't ignore it, ask a question.

  13. The Following User Says Thank You to Norm For This Useful Post:

    tcao2 (May 5th, 2012)

Similar Threads

  1. I REALLY NEED HELP IN SOLVING THIS ROCK PAPER SCISSOR
    By John93 in forum Java Theory & Questions
    Replies: 12
    Last Post: April 8th, 2012, 08:55 PM
  2. Solving a polynomial
    By arvindbis in forum Java Theory & Questions
    Replies: 9
    Last Post: March 8th, 2012, 12:16 AM
  3. Recursive Maze Help
    By chono in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 22nd, 2012, 08:02 PM
  4. Mouse Maze..Plz Help
    By TiT_4_tAt in forum What's Wrong With My Code?
    Replies: 3
    Last Post: February 19th, 2012, 07:33 AM
  5. Problem in recursion for Solving Maze Recursively program
    By _Coder1985 in forum Algorithms & Recursion
    Replies: 1
    Last Post: April 29th, 2009, 04:37 AM