Skip to content

Instantly share code, notes, and snippets.

@arnabmitra
Created October 30, 2016 04:42
Show Gist options
  • Save arnabmitra/d441ca03daca61106727b96da67dec29 to your computer and use it in GitHub Desktop.
Save arnabmitra/d441ca03daca61106727b96da67dec29 to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.stream.IntStream;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scanner = new Scanner(System.in);
int myInt = scanner.nextInt();
char[][] matrix =new char[myInt][myInt];
for(int i=0;i<myInt;i++) {
String myString = scanner.next();
int k=i;
IntStream.range(0,myString.length())
.forEach(c -> matrix[k][c]=myString.charAt(c));
}
scanner.close();
displayPathtoPrincess(myInt, matrix);
}
static void displayPathtoPrincess(int n,char[][] grid)
{
// initial
PathStep step = new PathStep((n-1)/2,(n-1)/2 , null,null);
LinkedList<PathStep> queue = new LinkedList<>();
queue.add(step);
// using set to check if already traversed
HashSet<Integer> set = new HashSet<>();
boolean findDest = false;
while(!queue.isEmpty() && !findDest) {
LinkedList<PathStep> tmpQueue = new LinkedList<>();
while(!queue.isEmpty()) {
step = queue.remove();
int i = step.i, j = step.j, id;
if(grid[i][j] == 'p') { // find dest
findDest = true;
break;
}
PathStep next;
// move left
if(j > 0 ) {
id = n * i + (j - 1);
if(!set.contains(id)) {
set.add(id);
next = new PathStep(i, j - 1, step,"LEFT");
tmpQueue.add(next);
}
}
// move right
if(j < n - 1) {
id = n * i + (j + 1);
if(!set.contains(id)) {
set.add(id);
next = new PathStep(i, j + 1, step,"RIGHT");
tmpQueue.add(next);
}
}
// move up
if(i > 0) {
id = n * (i - 1) + j;
if(!set.contains(id)) {
set.add(id);
next = new PathStep(i - 1, j, step,"UP");
tmpQueue.add(next);
}
}
// move down
if(i < n - 1) {
id = n * (i + 1) + j;
if(!set.contains(id)) {
set.add(id);
next = new PathStep(i + 1, j, step,"DOWN");
tmpQueue.add(next);
}
}
}
queue = tmpQueue;
}
if(findDest) {
// build path
ArrayList<PathStep> path = new ArrayList<>();
while(step != null) {
path.add(step);
step = step.prev;
}
Collections.reverse(path);
// print path
for(int i = 1; i < path.size(); i++) {
System.out.println(path.get(i));
}
}
}
static class PathStep {
int i, j;
PathStep prev;
String direction;
public PathStep(int i, int j, PathStep prev,String direction) {
this.i = i;
this.j = j;
this.prev = prev;
this.direction=direction;
}
public String toString() {
return direction;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment