Maze Solver in Java

Reading time ~10 minutes

Really nice way to check a potential candidate problem-solving skills is to test him as a mouse. How to find the way out of the maze? Programmically, of course.

From life experience we know, that the simpliest way to get out is to follow the right side and eventually we will find the exit.

Here is an example of the maze:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
+--+--+--+--+--+--+--+--+--+--+
|             S|     |     |  |
+  +--+--+--+  +--+  +  +  +  +
|     |  |     |     |  |  |  |
+--+  +  +  +--+  +--+--+  +  +
|     |  |        |     |     |
+  +--+  +--+--+--+  +  +  +--+
|     |        |     |        |
+--+  +--+  +  +  +--+--+--+  +
|  |  |  |  |     |           |
+  +  +  +  +--+--+  +--+--+--+
|           |     |        |  |
+--+  +--+--+  +--+--+--+  +  +
|     |        |     |     |  |
+  +--+  +--+  +  +--+  +--+  +
|  |     |  |  |     |      F |
+  +  +--+  +  +--+  +--+--+  +
|  |  |     |     |  |     |  |
+  +  +  +--+--+  +  +  +--+  +
|     |              |        |
+--+--+--+--+--+--+--+--+--+--+

The goal is to start from S and find F. Here is a possible solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

class coord{
	public int i;
	public int j;
	public coord(int i, int j){
		this.i = i;
		this.j = j;
	}
}

//Directions: 1 - right, 2 - up, 3 - left, 4 - down

public class Maze_solver {
	static String maze_filename = "maze.txt";
	static String route = "";
	static int last_move_direction = 2; //guess first direction
	static int[] directions = new int[]{4,1,2,3,4,1,2,3,4};	
	static boolean foundWayOut = false;
	@SuppressWarnings("serial")
	static HashMap<Integer, Character> direction_letters = new HashMap<Integer, Character>();
	                                  
	public static void main(String[] args) throws FileNotFoundException {
		initDirectionLetters()
		char[][] maze = readMaze(maze_filename);
		printMaze(maze);
		getOut(maze);
	}
	
	private void initDirectionLetters(){
		direction_letters.put(1, 'r');
		direction_letters.put(2, 'u');
		direction_letters.put(3, 'l');
		direction_letters.put(4, 'd');
	}
	
	private static char[][] readMaze(String filename) throws FileNotFoundException{
		Scanner sc = new Scanner(new BufferedReader(new FileReader(filename)));
		ArrayList<String> input = new ArrayList<String>();
		while (sc.hasNext())
			input.add(sc.nextLine());
		sc.close();
		
		int width = input.get(0).length(); 
		int height = input.size();		
		char[][] maze = new char[height][width];
		
		for (int j=0; j<height; j++){
			String line = input.get(j);
			for (int i=0; i < width; i++){
				maze[j][i] = line.charAt(i);
			}
		}
		
		return maze;
	}
	
	private static void printMaze(char[][] maze){
		for (int i=0; i < maze.length; i++){
			for (int j=0; j < maze[0].length; j++){
				System.out.print((char)maze[i][j]);
				System.out.print(" ");
			}
			System.out.println();
		}
	}
	
	private static void getOut(char[][] maze){
		coord coord = findStart(maze);
	    while (!foundWayOut){
	    	coord = makeMove(maze, coord);
	    	printMaze(maze);
	    }
		System.out.println(route);
	}
	
	static coord move(coord coord, int direction){
        coord new_coord = new coord(coord.i, coord.j);
        switch (direction){
        	case 1:
        		new_coord.j++;
        		break;
        	case 2:
        		new_coord.i--;
        		break;
        	case 3:
        		new_coord.j--;
        		break;
        	case 4:
        		new_coord.i++;
        		break;
        }        
        return new_coord;
    }
	
    static boolean checkIfGoodState(char[][] maze, coord coord){
    	if (maze[coord.i][coord.j] == 'F')
    		foundWayOut = true;
        return (maze[coord.i][coord.j] == ' ') ? true : false;
    }
    
    static coord makeMove(char[][] maze, coord coord){
        //try to do moves according to priority and break  
    	coord new_coord = null;
    	for (int i = last_move_direction - 1; i <= last_move_direction + 3; i++){
    		new_coord = move(coord, directions[i]);
    		if (checkIfGoodState(maze, new_coord)){
    			last_move_direction = directions[i];
    		    route += direction_letters.get(directions[i]);
    		    maze[new_coord.i][new_coord.j] = 'S';
    		    maze[coord.i][coord.j] = ' ';
    		    return new_coord;
    		}
    	}  		        
        return null; //shouldnt happen by assumption
    }
    
    static coord findStart(char[][] maze){
    	coord coord = new coord(0, 0);
        for (int i = 0; i < maze.length; i ++){
            for (int j = 0; j < maze[1].length; j ++){
               if (maze[i][j] == 'S'){
            	   coord.i = i;
            	   coord.j = j;
                   break;
               }
            }
        }
        return coord;
    }
}

How to Download Multiple Instagram Photos at Once?

You want to print your Insta photos or just keep them save and archived? Out of luck - there is no obvious way to download them, unless y...… Continue reading

Polymer and Vulcanization

Published on August 08, 2016

Jeff Dean of Google

Published on August 06, 2016