Amazon Interview Question
SDE1sCountry: India
Interview Type: In-Person
Here's an implementation of @Anonymous suggestion in C++
#include<stdio.h>
#include<iostream>
#include<string.h>
#define N 4
#define M 5
using namespace std;
// Prints the nearest bathroom
void printNearestBathroom(int rowPos,int colPos) {
cout<<"The nearest bathroom is at:"<<rowPos<<" "<<colPos;
return;
}
void bfs(int matrix[][M],int startPosRow,int startPosCol) {
int queue[N*M][2];
bool visited[N][M];
for(int i=0;i<N;i++) {
for(int j=0;j<M;j++) {
visited[i][j]=false;
}
}
int front,rear;
front=rear=-1;
queue[++rear][0]=startPosRow;
queue[rear][1]=startPosCol;
visited[startPosRow][startPosCol]=true;
front++;
while(front<=rear) {
int currRow=queue[front][0];
int currCol=queue[front][1];
if(matrix[currRow][currCol]==0) {
printNearestBathroom(currRow,currCol);
return;
}
front++;
if( currRow>0 && visited[currRow-1][currCol]==false ) {
queue[++rear][0]=currRow-1;
queue[rear][1]=currCol;
visited[currRow-1][currCol]=true;
}
if(currCol>0 && visited[currRow][currCol-1]==false ) {
queue[++rear][0]=currRow;
queue[rear][1]=currCol-1;
visited[currRow][currCol-1]=true;
}
if(currCol!=M-1 && visited[currRow][currCol+1]==false ) {
queue[++rear][0]=currRow;
queue[rear][1]=currCol+1;
visited[currRow][currCol+1]=true;
}
if(currRow!=N-1 && visited[currRow+1][currCol]==false ) {
queue[++rear][0]=currRow+1;
queue[rear][1]=currCol;
visited[currRow+1][currCol]=true;
}
}
}
int main() {
int matrix[N][M]={ {1,1,1,1,0}, // 1 denotes a room and 0 denotes a bathroom
{1,1,1,1,1},
{1,1,0,1,0},
{1,1,0,1,0}
};
bfs(matrix,2,1);
return 0;
}
One way is to maintain a count variable and recursively call for the left, right, bottom and up from the room and increment the count unless a bathroom is reached. Once reached compare the count with max. If less than max then update. Finally the minimum is the answer.
Second is using DP, which needs to be modified to start from the given room.
Since there are multiple bathrooms available, I think it is better if we consider a single-source shortest path algorithm other than BSF/DFS. As a result, we will find the distance to all the bathrooms. The answer to this problem is then the shortest path found in the process. If we are ensured that weights are all positive, then Dijkstra can be used safely. Otherwise, it is a safer bet to use Bellman-Ford algorithm to address the possibility of existence of any negatively weighted edge.
You can see the matrix as a graph, with the doors being edges. Then simply do a BFS from the room you're at, and once you hit a bathroom, return its location.
- Anonymous July 11, 2013