Skip to content

Instantly share code, notes, and snippets.

@manuel-delverme
Last active December 11, 2015 13:54
Show Gist options
  • Save manuel-delverme/23a136103731fda082fc to your computer and use it in GitHub Desktop.
Save manuel-delverme/23a136103731fda082fc to your computer and use it in GitHub Desktop.
ex9.c
#include <stdio.h>
#include <stdlib.h>
#define N_ROWS 5
#define N_COLS 5
void main(){
char swamp[N_ROWS][N_COLS] = {
{'*' , '*', '.', '*', '.' },
{'.' , '.', '.', '.', '.' },
{'.' , '.', '*', '.', '*' },
{'.' , '*', '.', '*', '*' },
{'*' , '.', '.', '.', '*' }
};
char steps[N_COLS - 1];
int im_stuck;
int r, c;
int starting_row;
im_stuck = 1;
// for each starting position
for(starting_row = 0; starting_row < N_ROWS; starting_row++){
// we try to start moving from each position
// the first time is the row number 0
// if row 0 fails we try with row number 1 etc..
printf("starting from row: %d\n", starting_row);
// if we start in a bad position
if(swamp[starting_row][0] == '.'){
// skip this position and
// go to the next
printf("blah im in the mud\n\n");
continue;
}
// if im_stuck is still 0 when the for( int c .. loop finished
// then we didn't get stuck and reached the end of the swamp
// so inside the steps[] array there is the solution
if (im_stuck == 0){
break;
}
// the program works when/if im_stuck doesn't change
im_stuck = 0;
// the first step is where we start from
r = starting_row;
// the columns steps to the right
for(c = 0; c < (N_COLS - 1); c++){
// printf("i'm at col %d\n", c);
printf("i see:\n%c\n%c\n%c\n", swamp[r+1][c+1], swamp[r][c+1], swamp[r-1][c+1]);
// check if there is a star on the square right-above
// but also check that a right-below square exists
if((r != N_ROWS ) && (swamp[r+1][c+1] == '*') ){
printf("%d,%d is good\n", r+1, c+1);
// the next row will be up
r = r + 1;
steps[c] = 'v';
}
// if there isnt a star on the square right-above
// but there is a star in front of us
else if(swamp[r][c+1] == '*'){
printf("step right to (%d,%d)\n", r, c+1);
// the next move will be on the same row
r = r;
steps[c] = '>';
}
// if there isnt a star on the square right-above or in front
// but there is a star right-below
else if((r != 0 ) && (swamp[r-1][c+1] == '*') ){
printf("step up to (%d,%d)\n", r-1, c+1);
// the next move will be down
r = r - 1;
steps[c] = '^';
} else {
// if there were no stars
// we got stuck, and the program will try with another
// starting position
printf("stuck at (%d, %d)\n", r, c);
// raise the IM STUCK flag
im_stuck = 1;
printf("path was: %s\n", steps);
// go back to try starting in a different row
break;
}
}
}
printf("a good path is:");
printf("%d", starting_row - 1);
printf("%s\n", steps);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment