Wednesday, March 1, 2017

Path traversal

Given a matrix with 0’s and 1’s , you enter the matrix at cell (0,0) in left to right direction. whenever you encounter a 0 you retain in same direction , if you encounter a 1’s you have to change direction to right of current direction and change that 1 value to 0, you have to find out from which index you will leave the matrix at the end.

Input:
3 3
0 0 1 0 0 0 0 0 0

Output:
2 2 

Input:
2 4
0 0 0 1 0 0 1 1

Output:
0 2

Example: The matrix will be represented as
0 1 1 1 0 
1 0 1 0 1 
1 1 1 0 0

The path is 
(0,0) (0,1) (1,1) (2,1) (2,0) (1,0) (1,1) (1,2) (2,2) (2,1) (2,0)


Answer:

Check my geeksforgeeks submission: http://www.practice.geeksforgeeks.org/viewSol.php?subId=1574427&pid=1586

#include <stdio.h>

// RR = Row Right
// CD = Column Down
// RL = Row Left
// CU = Column Up
enum state { RR, CD, RL, CU};

void change_state(int *curstate)
{
if(*curstate == CU)
*curstate = RR;
else 
  *curstate = *curstate + 1;
}

void parse_state(int *curstate, int *i, int *j)
{
printf(" %d,%d\n",*i,*j);
switch(*curstate) {
case RR:
*j = *j + 1;
break;
case CD:
*i = *i + 1;
break;
case RL:
*j = *j - 1;
break;
case CU:
*i = *i - 1;
break;
default:
break;
}
}

void print_exitpath(int r, int c, int (*p)[10][10]) {
int i=0,j=0;
int curstate = RR;

 while((i>=0) && (i<x) && (j>=0) && (j<y)) {
if((*p)[i][j] == 1) {
(*p)[i][j] = 0;
change_state(&curstate);
}
parse_state(&curstate, &i, &j);
}
}

int main(void) {
int r, c,i,j;
int a[10][10];

printf("r: ");
scanf("%d",&r);
printf("c: ");
scanf("%d",&c);
for(i=0; i < r ; i++) {
for(j=0; j
printf("Value[%d][%d]: ",i,j);
scanf("%d",&a[i][j]);
}
}

print_exitpath(r,c,&a);
return 0;
}

1 comment:

Path Traversal said...

Very nice blog... It was really a perfect guide for all path traversal learners. Thanks for sharing useful information.