#include #include char *InName = "day1c.dat"; char *OutName = "day1c.sol"; #define FALSE 0 #define TRUE !FALSE; const int MAXSIZE = 10; const int N = 4; // Size of array int Cube[MAXSIZE + 2][MAXSIZE + 2]; int Visited[MAXSIZE+2][MAXSIZE + 2]; const int MAXHEIGHT = 8; const int WALLHEIGHT = MAXHEIGHT + 2; void ReadInput(char *InName) { ifstream in(InName, ios::nocreate); if(in == NULL) { cerr << "Error Opening " << InName << endl; exit(1); } else { int row, col; for(row = 0; row <= N + 1; row++) for(col = 0; col <= N + 1; col++) { Cube[row][col] = WALLHEIGHT; // Ensure can't walk off Visited[row][col] = FALSE; } for(row = 1; row <= N; row++) for(col = 1; col <= N; col++) { in >> Cube[row][col]; if(Cube[row][col] < 0 || Cube[row][col] > MAXHEIGHT) { cerr << "Error bad height\n"; exit(2); } } in.close(); } } CanStep(int diff) { return (diff == -1 || diff == 0 || diff == 1); } int Straight() { int max = 1, walk = 1; int row, col; // Start off with walks along the rows for(row = 1; row <= N; row++) { walk = 1; for(col = 1; col <= N - 1; col++) { if(CanStep(Cube[row][col] - Cube[row][col+1])) walk++; else { walk = 1; if(walk > max) // End of walk, check max length max = walk; } } if(walk > max) // check max length max = walk; } // Now try walks down the columns for(col = 1; col <= N; col++) { walk = 1; for(row = 1; row <= N - 1; row++) { if(CanStep(Cube[row][col] - Cube[row+1][col])) walk++; else if(walk > max) // check max length { max = walk; walk = 1; } } if(walk > max) // check max length max = walk; } return max; } int WalkLen = 0; int MaxLen = 0; void Search(int row, int col, int LastHeight) { if(!Visited[row][col] && CanStep(LastHeight - Cube[row][col])) { //cout << row << ", " << col << " = " << Cube[row][col] << endl; if(row < 1 || row > N || col < 1 || col > N ||Cube[row][col] > MAXHEIGHT) { cerr << "error"; exit(3); } // One more item in the walk Visited[row][col] = TRUE; WalkLen++; if(WalkLen > MaxLen) MaxLen = WalkLen; int Height = Cube[row][col]; // Try all four directions Search(row+1, col, Height); Search(row-1, col, Height); Search(row, col+1, Height); Search(row, col-1, Height); // BackTrack Visited[row][col] = FALSE; WalkLen--; } } int main() { ReadInput(InName); // Part one, find the longest length can walk int row, col; ofstream out(OutName); out << Straight() << endl; // Try each starting position for the recursive search for(col = 1; col <= N; col++) for(row = 1; row <= N; row++) Search(row, col, Cube[row][col]); out << MaxLen << endl; out.close(); return 0; }