home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / qc_prog / chap07 / magic.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-04-05  |  2.2 KB  |  87 lines

  1. /* magic.c  --  demonstrate use of a two-dimensional  */
  2. /*              array of type int                     */
  3.  
  4. main()
  5. {
  6.     static int square[3][3] = { 5, 8, 3, 4, 2, 0, 7, 1, 6 };
  7.     int zrow = 1, zcol = 2;  /* location of the zero */
  8.     int num, row, col, i , j, rowdist, coldist;
  9.  
  10.     while (1)
  11.         {
  12.         printf("Swap what with zero?\n");
  13.         printf("(Q to quit)\n");
  14.  
  15.         /* Print the square. */
  16.         for (i = 0; i < 3; ++i)
  17.             {
  18.             for (j = 0; j < 3; ++j)
  19.                 {
  20.                 printf(" %d ", square[i][j] );
  21.                 }
  22.             printf("\n");
  23.             }
  24.  
  25.         /* Input the user number. */
  26.         if ((num = getch()) == 'Q')
  27.             exit(0);
  28.         num -= '0';
  29.         if (num < 1 || num > 9)
  30.             {
  31.             printf("Not a legal number.\n\n");
  32.             continue;
  33.             }
  34.  
  35.         /* Find that square. */
  36.         for (row = 0; row < 3; ++row)
  37.             {
  38.             for(col = 0; col < 3; ++col)
  39.                 {
  40.                 if (num == square[row][col])
  41.                     {
  42.                     goto GOTIT;
  43.                     }
  44.                 }
  45.             }
  46. GOTIT:
  47.         /* Check for a legal move. */
  48.         if (row > 2 || col > 2)
  49.             {
  50.             printf("Bad Box Specification\n\n");
  51.             continue;
  52.             }
  53.         rowdist = zrow - row;
  54.         if (rowdist < 0) 
  55.             rowdist *= -1;
  56.         coldist = zcol - col;
  57.         if (coldist < 0) 
  58.             coldist *= -1;
  59.         if (rowdist > 1 || coldist > 1)
  60.             {
  61.             printf("Not A Neighbor\n\n");
  62.             continue;
  63.             }
  64.  
  65.         /* Make the move. */
  66.         square[zrow][zcol] = square[row][col];
  67.         square[row][col] = 0;
  68.         zrow = row;
  69.         zcol = col;
  70.  
  71.         /* See if done, and solved. */
  72.         for (i = 0; i < 3; ++i)
  73.             {
  74.             for (j = 0; j < 3; ++j)
  75.                 {
  76.                 if (square[i][j] != ((i * 3) + j))
  77.                     {
  78.                     break;
  79.                     }
  80.                 }
  81.             }
  82.         if ((i * j) == 9)
  83.             break;
  84.         }
  85.     printf("\n\aYOU GOT IT !!!\n");
  86. }
  87.