/* Problem 1--Coast Tracker
   There are a couple of tricky special cases to adhere to the right-
   hand rule, but not many. */

#include <stdio.h>
#include <stdlib.h>

FILE *in, *out;
int M[3][3]; /* holds land/water information */

int main (int argc, char **argv);
int xcoord (int d);
int ycoord (int d);

int main (int argc, char **argv) {

  int x, y, d, i, xi, yi, si;

 in = fopen ("prob1.in","r");
 out = fopen ("prob1.out","w");
 while (fscanf (in,"%d",&x),x!=-1) {
  fscanf (in,"%d %d",&y,&d);
  for (i=0; i < 8; i++) { /* load land/water information */
   fscanf (in,"%d %d %d",&xi,&yi,&si);
   M[xi-x+1][yi-y+1] = si;
  }
  d -= d%2; /* If we're moving diagonally, align on the right edge */
  d = (d+7)%8; /* The first square to try */
  while (!M[xcoord(d)][ycoord(d)]) d=(d+1)%8; /* go through squares */
  fprintf (out,"%d\n",d); /* until we can find one to move to */
 }
 fclose (in);
 fclose (out);
 return EXIT_SUCCESS;
}

/* xcoord returns the x-coordinate of the square in the specified
   direction */
int xcoord (int d) {

 switch (d) {
  case 5: case 6: case 7: return 2;
  case 0: case 4: return 1;
  case 1: case 2: case 3: return 0;
 }
 return -1;
}

/* ycoord returns the y-coordinate of the square in the specified
   direction */
int ycoord (int d) {

 switch (d) {
  case 0: case 1: case 7: return 2;
  case 2: case 6: return 1;
  case 3: case 4: case 5: return 0;
 }
 return -1;
}

