## Samsung Interview Question

Software Engineer / Developers**Country:**India

**Interview Type:**In-Person

shortest distance between the first and the last element in a two dimension:

Case 1: first element = a[0][0] & last element a[M][N]

Sol: you can never move from a[0][0] to a[M][N] with only possible action left and down. Right move is required unless left move from a[0][0] is not a[0][N]

Case 2: first element = a[0][0] & last element a[M][index] (bottom row)

Sol: no matter what matrix is given made up with o and 1. ans will always M down moves.

Case 3: first element = a[0][0] & last element a[M][N] (right most column) and we have move down or right for each 1

Sol: when ever you got 1 go right and down for 0...once reached rightmost column go down for all elements (0 or 1)

There seems to be a problem with the mechanics of the question.

- You want to start at (0,0) and go to (m-1,n-1) in a m by n grid.

- As per your question, on seeing a 1 you can move left or down and on seeing a 0 you can move only down.

- The problem with this is that you are never able to move right and you may never reach (m-1, n-1).

So , the second part of your question ought to be something like this :

Given, if the element is 1, we can move LEFT or DOWN, if it is 0 we can move RIGHT or UPWARDS.

yeah Rahul you are correct, the question was if the element was 1 , we can move right or downwards and if it was 0, we can proceed downwards only. Also, we have to find whether the route from the (0,0) to (m-1,n-1) exists.

```
#include<stdio.h>
int findPath(int arr[][4],int posx, int posy, int maxx, int maxy)
{
int pathFound = 0;
printf("x:%d and y:%d\n",posx,posy);
if(posx < maxx && posy < maxy-1)
{
if(arr[posx][posy] == 1)
{
pathFound = findPath(arr,posx,posy+1,maxx,maxy);
}
if( pathFound == 0)
{
pathFound = findPath(arr,posx+1,posy,maxx,maxy);
}
}
else if(posy == maxx-1)
{
pathFound = 1;
}
return pathFound;
}
int main()
{
int arr[4][4] = {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,1,1,0}};
printf("%d",findPath(arr,0,0,4,4));
}
```

i think this works fine

Create a Graph from the given conditions, where each cell in the Matrix is a Node. Give each cell a number and when value is 0 it connects to two other cell through graph edge. When value is 1, it connects to only one cell.

After that run Graph Shortest path algorithm with same weight for each edge.

First place question should be "Given if the element is 1 we can move Right or down, if it is 0 we can only proceed downward".

Then find the working code.......

Plz give any comment....

- Rahul September 19, 2013