Advertisement
vbuterin

Canadian Computing Competition 2010 Junior 5 Solution

Jan 9th, 2012
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.03 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <iostream>
  4. #include <fstream>
  5. #include <string>
  6.  
  7. using namespace std;
  8. int min(int x1, int x2) {
  9.   if (x1 < x2) return x1;
  10.   else return x2;
  11. }
  12.  
  13. int main() {
  14.   int board[8][8];
  15.   int startx, starty;
  16.   cin >> startx;
  17.   cin >> starty;
  18.   //The contest starts indexing at one, not zero
  19.   startx -= 1;
  20.   starty -= 1;
  21.   for (int x = 0; x < 8; x++) {
  22.     for (int y = 0; y < 8; y++) {
  23.       board[x][y] = 999; //999 represents "unexplored by the program"
  24.     }
  25.   }
  26.   board[startx][starty] = 0;
  27.   int finalx, finaly;
  28.   cin >> finalx;
  29.   cin >> finaly;
  30.   finalx -= 1;
  31.   finaly -= 1;
  32.   //We'll make 64 passes over the board, since no two squares can possibly be more than 64 squares apart (a path contradicting this must pass over the same square twice, making it suboptimal). Usually a mere 1-3 passes will suffice since cells explored during a pass will become usable for the rest of the pass (eg. the program can go 1,1 -> 3,2 -> 4,4 -> 6,5 in one pass)
  33.   for (int t = 0; t < 64; t++) {
  34.     for (int x = 0; x < 8; x++) {
  35.       for (int y = 0; y < 8; y++) {
  36.         //The basic trick here is that if a cell takes N moves to it, the cell 1 move away will take N+1 moves unless there is another, shorter path to it
  37.         if (board[x][y] < 999) {
  38.       if (x>1 && y>0) board[x-2][y-1] = min(board[x-2][y-1],board[x][y]+1);
  39.       if (x>1 && y<7) board[x-2][y+1] = min(board[x-2][y+1],board[x][y]+1);
  40.       if (x>0 && y>1) board[x-1][y-2] = min(board[x-1][y-2],board[x][y]+1);
  41.       if (x>0 && y<6) board[x-1][y+2] = min(board[x-1][y+2],board[x][y]+1);
  42.       if (x<7 && y>1) board[x+1][y-2] = min(board[x+1][y-2],board[x][y]+1);
  43.       if (x<7 && y<6) board[x+1][y+2] = min(board[x+1][y+2],board[x][y]+1);
  44.       if (x<6 && y>0) board[x+2][y-1] = min(board[x+2][y-1],board[x][y]+1);
  45.       if (x<6 && y<7) board[x+2][y+1] = min(board[x+2][y+1],board[x][y]+1);
  46.     }
  47.       }
  48.     }
  49.     if (board[finalx][finaly] < 999) {
  50.       cout << board[finalx][finaly] << "\n"; //We found it, report and abort
  51.       return 0;
  52.     }
  53.   }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement