0

Here is the maze traversal method and full code

import java.io.*;
import java.util.*;

public class Quest {

    static char[][] maze = new char[10][10];
    public static void main(String[] args) throws IOException {
       Scanner scan = new Scanner(new File("quest.dat"));
       String s = "";
       int n = scan.nextInt();
       scan.nextLine();

       while (n-->0) {
          for (int i=0; i<10; i++) {
            s = scan.nextLine();
            if (s.equals("-"))
              break;
          for (int j=0; j<10; j++)
            maze[i][j] = s.charAt(j);
       }
       int r = searchR();
       int c = searchC();
       //System.out.println(r + " " + c);
       mazeTraverse(r, c);
       for (int i=0; i<10; i++) {
         for (int j=0; j<10; j++)
           System.out.print(maze[i][j]);
         System.out.println();
     }
   }
}
public static void mazeTraverse(int r, int c) {
if ((r>0 && r<maze.length && c>0 && c<maze.length) && maze[r][c] == 'H')
  return;
if ((r>0 && r<maze.length && c>0 && c<maze.length) && (maze[r][c]=='.' || maze[r][c]=='A')) {
  if (!(maze[r][c]=='A'))
    maze[r][c] = 'O';

        mazeTraverse(r+1, c);
        mazeTraverse(r-1, c);
        mazeTraverse(r, c+1);
        mazeTraverse(r, c-1);

        maze[r][c] = '.';
   }
}

public static int searchR() {
for (int r=0; r<10; r++) {
  for (int c=0; c<10; c++) {
    if (maze[r][c]=='A')
      return r;
  }
}
return -1;
}
public static int searchC() {
   for (int r=0; r<10; r++) {
     for (int c=0; c<10; c++) {
       if (maze[r][c]=='A')
         return c;
     }
   }
   return -1;
   }
}

When I run the program it just continuously runs and doesn't stop, but I checked and I am getting the correct r and c values so what could be the problem? The mazes are 10x10 so they are perfect squares.

1 Answers1

0

Meta talk: is it bad if I leave this answer here knowing that it is wrong if I'm trying to get the Peer Pressure badge?


You are checking r and c to be less than the "length" of the maze array, but maze is 2D. This means there are 2 lengths to check. (Imagine the array as a rectangle. There is a length but also a height and they might not be the same.)

c<maze.length

This check will not help you because c is used in the second index.

Try

c < maze[0].length //however, this assumes that there is at least one element in the array

Example:

Say the size of maze is 5x3. maze.length will give 5, and maze[0].length will give 3. Your check will see if c is less than 5. 4 is less than 5, but not less than 3, so you will get an out of bounds exception.

Arc676
  • 4,445
  • 3
  • 28
  • 44