Amazon Interview Question
SDE-3sCountry: United States
Interview Type: In-Person
For both parts of the question, the right way to go seems BFS.
For the first part the start position would be the random input point and stop when you reach a door.
For the second part enqueue all the points where there are doors. Each position gets its discoverer's distance plus 1. Stop when the queue is empty.
Note that it's possible that one or more points are left unmarked. These points don't have access to any door and can be marked with -1 or MAXINT after the BFS process completes.
BFS is the right way to go ... Also you can create an adapter class for the grid/matrix to navigate from any node in the four possible directions and simply use the text book algorithm for BFS. Below is a C# implementation
public enum NodeStatus
{
Undiscovered,
Discovered,
Processed
}
/// <summary>
/// Adapter class to convert the matrix into a graph
/// <remarks>we can do without this class but this makes it cleaner</remarks>
/// </summary>
public class Node
{
private static Dictionary<string, Node> TempDic = new Dictionary<string, Node>();
public int X { get; private set; }
public int Y { get; private set; }
public Node Parent { get; set; }
public NodeStatus Status { get; set; }
public int Distance { get; set; }
public char GetValue(char[,] g)
{
if (IsValid(X, Y, g))
{
return g[X, Y];
}
else
{
throw new Exception("Invalid Indicies!");
}
}
public List<Node> AdjNodes(char[,] g)
{
List<Node> nodes = new List<Node>();
Node n = GetNode(X + 1, Y, g);
if (n != null)
{
nodes.Add(n);
}
n = GetNode(X - 1, Y, g);
if (n != null)
{
nodes.Add(n);
}
n = GetNode(X, Y + 1, g);
if (n != null)
{
nodes.Add(n);
}
n = GetNode(X, Y - 1, g);
if (n != null)
{
nodes.Add(n);
}
return nodes;
}
private static bool IsValid(int x, int y, char[,] g)
{
return (x >= 0 && x < g.GetLength(0)) && (y >= 0 && y < g.GetLength(1));
}
public static Node GetNode(int x, int y, char[,] g)
{
if (IsValid(x, y, g))
{
string key = string.Format("{0},{1}", x, y);
if (!TempDic.ContainsKey(key))
{
TempDic[key] = new Node { X = x, Y = y };
}
return TempDic[key];
}
else
{
return null;
}
}
public static void Clear()
{
TempDic.Clear();
}
}
public static List<Node> FindNearest(int x, int y, char[,] g, char t)
{
Node.Clear();
Node s = Node.GetNode(x, y, g);
if (s == null)
{
throw new Exception("Invalid indicies");
}
Queue<Node> q = new Queue<Node>();
q.Enqueue(s);
int dist = -1;
List<Node> nodes = new List<Node>();
while (q.Count > 0)
{
Node c = q.Dequeue();
c.Status = NodeStatus.Processed;
foreach (var adjNode in c.AdjNodes(g))
{
if (adjNode.Status == NodeStatus.Undiscovered)
{
q.Enqueue(adjNode);
adjNode.Parent = c;
adjNode.Distance = c.Distance + 1;
}
}
if (c.GetValue(g) == t)
{
if ((dist == -1 || dist >= c.Distance) && !nodes.Contains(c))
{
nodes.Add(c);
dist = c.Distance;
}
}
}
foreach (var n in nodes)
{
Console.WriteLine();
string key = string.Format("{0},{1}", n.X, n.Y);
Console.WriteLine("To :"+key + " Distance:"+n.Distance);
PrintPath(n);
}
return nodes;
}
public static void PrintPath(Node n)
{
if (n == null)
return;
PrintPath(n.Parent);
string key = string.Format("{0},{1}", n.X, n.Y);
Console.WriteLine(key);
}
char[,] g = new char[,]
{
{'w', 'w', 'e', 'w', 'd' },
{'w', 'w', 'e', 'w', 'd' },
{'w', 'w', 'd', 'w', 'd' }
};
.FindNearest(0, 0, g, 'd');
Java solution :
//Algo:
1st part: Use BFS to find the distance from the input random coordinate to the nearest door.
2nd part: Insert all the door coordinates with distance 0 into the queue. Now run BFS.
We are doing this because we want the distance to be updated from all directions. Spreading the gossip from all sources. :)
Maintain a third 2D array which will hold the distances. Then return this distance array.
import java.io.*;
import java.util.*;
class Coordinate {
int x,y;
Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}
class Array {
public static final int grid[][] = {
{2, 1, 2, 1, 2, 2, 2},
{2, 0, 2, 0, 0, 0, 2},
{2, 0, 0, 0, 2, 0, 2},
{2, 2, 0, 2, 0, 0, 2},
{2, 0, 0, 0, 0, 0, 2},
{2, 2, 2, 0, 0, 0, 2},
{2, 2, 2, 2, 2, 2, 2}};
static final int moves[][] = {{1,0,-1,0},
{0,1,0,-1}};
public static void main (String[] args) {
System.out.print(getMinDist(grid,2,3));
}
static int getMinDist(int grid[][], int m, int n) {
if(grid[m][n] == 2)
return -1;
if(grid[m][n] == 1)
return 0;
int visited[][] = new int[grid.length][grid[0].length];
int dist = getMinDistUtil(grid,m,n,visited);
return dist;
}
static int getMinDistUtil(int grid[][], int m, int n, int visited[][]) {
visited[m][n] = 1;
Queue<Coordinate> queue = new LinkedList<>();
queue.add(new Coordinate(m,n));
// get neighbors and add to queue if valid
while(!queue.isEmpty()) {
Coordinate coor = queue.poll();
int dist = visited[coor.x][coor.y];
System.out.println("dist : " + dist + " x,y " + coor.x + "," + coor.y);
if(grid[coor.x][coor.y] == 1)
return (dist - 1);
for(int i=0; i<moves[0].length; i++) {
int X = coor.x + moves[0][i];
int Y = coor.y + moves[1][i];
System.out.println("X,Y : " + X + "," + Y);
if(X >= 0 && X < grid.length &&
Y >= 0 && Y < grid[0].length &&
grid[X][Y] != 2 && visited[X][Y] == 0)
{
visited[X][Y] = dist + 1;
queue.add(new Coordinate(X,Y));
}
}
}
return -1;
}
}
- Anonymous March 11, 2017