I need to output the shortest directions from 'P' to 'G'. I have used BFS for to implement it. The problem is as shown below:
Input: 'N' dimension maze '#' - Wall 'G' - Ghost 'P' - Pacman
//Input Maze
8
########
# #
# # ## #
# # #G#
#P ###
#### # #
#G #G#
########
Output: directions in N/S/W/E
EX) E E E S S W W W
I keep getting time limit exceeded for my code. I can't pinpoint exactly where it may be the problem. My code is as follows:
I made a 'Point' class for the directions and the coordinates.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Maze{
static char[][] map;
static boolean[][] visited;
static int[] dr = {1,-1,0,0};
static int[] dc = {0,0,-1,1};
static String[] compass = {"S","N","W","E"};
static int cur_x, cur_y, cur_dist, N;
static String nswe = "";
static String curnswe = "";
static String oldDir, dir;
static int sx, sy;
static int shortestDist;
public static class Point{
int x;
int y;
int dist;
String ns;
String dir;
public Point(int x, int y, int dist, String oldDir, String dir){
this.x = x;
this.y = y;
this.dist = dist;
if("".equals(oldDir)) {
this.ns = dir;
}
else { this.ns = oldDir + " " + dir;
}
}
}
This is the BFS method():
public static void bfs(int x, int y, int dist, String oldDir, String dir){
Queue<Point> q = new LinkedList<Point>();
q.offer(new Point(x,y,dist,oldDir,dir));
while(!q.isEmpty()){
Point cur = q.poll();
cur_x = cur.x;
cur_y = cur.y;
cur_dist = cur.dist;
curnswe = cur.ns;
nswe = curnswe;
if(map[cur_x][cur_y]=='G') {
return;
}
for(int dir1 = 0; dir1<4; dir1++){
int r = cur_x + dr[dir1];
int c = cur_y + dc[dir1];
String d = compass[dir1];
if(r >= 0 && c >= 0 && r < N && c < N){
if(map[r][c]!='#')
if(!visited[r][c]){
q.offer(new Point(r,c,cur_dist+1,curnswe,d));
visited[r][c] = true;
}
}
}
}
q.clear();
}
This is the main part of the code where I input the maze, solve (BFS), and print out the directions.
public static void main(String[] args) throws IOException{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(input.readLine());
N = Integer.parseInt(st.nextToken());
int dist = 1;
map = new char[N][N];
visited = new boolean[N][N];
for(int i=0;i<N;i++){
String line = input.readLine();
for (int j=0; j<N; j++) {
char t = line.charAt(j);
if(t=='P') {sx=i; sy=j;}
map[i][j] = line.charAt(j);
}
}
bfs(sx,sy,dist,"","");
output.write(nswe + " ");
output.flush();
}
}