rendered paste bodyimport java.io.*;
class MazeMarkPath {
public static void main(String[] args) throws Exception {
BufferedReader fin = new BufferedReader( new FileReader("DATAMAZE.txt"));
main(fin);
fin.close();
}
static char[][] maze;
static int rows, cols;
static final char EMPTY = '.';
static final char MARKED = '#';
static final char START = 'S';
static final char END = 'E';
static final char WALL = 'X';
static int[] markx;
static int[] marky;
private static void main(BufferedReader fin) throws IOException {
/* getting input */
String temp = fin.readLine();
rows = Integer.parseInt( temp.substring(0, temp.indexOf(' ') ) );
cols = Integer.parseInt( temp.substring(temp.indexOf(' ') + 1));
maze = new char[rows+2][cols+2];
int startx = -1;
int starty = -1;
//top and bottom border
for (int i = 0; i <maze[0].length; i++) {
maze[0][i] = maze[maze.length - 1][i] = WALL;
}
for (int i = 1; i < maze.length - 1; i++) {
temp = fin.readLine();
maze[i][0] = maze[i][maze[0].length-1] = WALL; //left and right border
for (int j = 1; j < maze[0].length - 1; j++) {
maze[i][j] = temp.charAt(j -1);
if (maze[i][j] == START) {
startx = j;
starty = i;
}
}
}
markx = new int[rows * cols + 1];
marky = new int[rows * cols + 1];
for (int i = 0; i < markx.length; i++) {
markx[i] = marky[i] = -1;
}
print(maze);
System.out.println(starty + " " + startx);
System.out.println(findPath(startx, starty, 0));
mark();
print(maze);
}
private static int findPath(int x, int y, int depth) {
if (maze[y][x] == END) {
return 0;
} else {
if (maze[y][x] == EMPTY) {
maze[y][x] = MARKED;
}
int min = rows * cols + 1;
int temp;
//up
if (isOK( maze[y+1][x] ) ) {
temp = findPath(x, y+1, depth+1);
if (temp < min) {
min = temp;
markx[depth+1] = x;
marky[depth+1] = y+1;
}
}
//down
if (isOK( maze[y-1][x] ) ) {
temp = findPath(x, y-1, depth+1);
if (temp < min) {
min = temp;
markx[depth+1] = x;
marky[depth+1] = y-1;
}
}
//right
if (isOK( maze[y][x+1] ) ) {
temp = findPath(x+1, y, depth+1);
if (temp < min) {
min = temp;
markx[depth+1] = x+1;
marky[depth+1] = y;
}
}
//left
if (isOK( maze[y][x-1] ) ) {
temp = findPath(x-1, y, depth+1);
if (temp < min) {
min = temp;
markx[depth+1] = x-1;
marky[depth+1] = y;
}
}
if (maze[y][x] == MARKED) {
maze[y][x] = EMPTY;
}
return 1 + min;
}
}
private static boolean isOK(char c) {
return (c == EMPTY || c == END);
}
private static void mark() {
for (int i = 1; markx[i] > 0; i++) {
if (maze[marky[i]][markx[i]] == EMPTY)
maze[marky[i]][markx[i]] = MARKED;
}
}
private static void print(char[][] c) {
for (int i = 0; i < c.length ;i++) {
for (int j = 0; j < c[0].length ; j++) {
System.out.print(c[i][j]);
}
System.out.println();
}
}
}