const int MAXROWS = 4;
const int MAXCOLS = 4;
const int MAXFILENAME = 255;
// Structure used to define a point (x,y) in the grid.
typedef struct
{
int x, y;
} Point;
// Structure used to store a partially filled array, consisting of an
// array of integers and it's used size (number of filled positions).
typedef struct
{
int list[MAXROWS * MAXCOLS];
int size;
} Sequence;
// Prints the contents of the nums array to the screen
// from position 0 to position usedSize-1.
void printArray(const int nums[], int usedSize);
// Finds and returns the longest increasing sequence of numbers in grid, beginning at startPos.
// The value found at position startPos in the grid will be the first number in the returned sequence.
// Note: this is a helper function which is used to start the recursive generateSeq function.
Sequence getSequence(int grid[][MAXCOLS], Point startPos);
// Finds and returns the longest increasing sequence of numbers in grid, beginning at startPos.
// seq is the sequence which has been found so far.
Sequence generateSeq(int grid[][MAXCOLS], Point startPos, Sequence seq);
int main()
{
int grid[MAXROWS][MAXCOLS]; // Holds the grid, as read from the file
char filename[MAXFILENAME]; // Holds the filename of the grid file
Sequence maxseq; // Holds the max sequence found in the grid
Point startPos; // The position in the grid of where the sequence begins
cout << "Enter filename containing grid: ";
cin.getline(filename, MAXFILENAME);
Sequence tmpseq;
maxseq.size = 0;
ifstream input;
input.open(filename);
if (input.fail())
{
cout << "ERROR: input file cannot be opened.\n";
return 1;
}
// these two nested for loops read the first number from the file and place in the array named grid.
for(int y=0; y < MAXROWS; y++)
{
for(int x=0; x <MAXCOLS; x++)
{
input >> grid[y][x];
//cout << x << " " << y << " " << grid[y][x] << "\n";
}
}
input.close();
//these two nested for loops assign x and y as values for the start position on the grid.
for(int y=0; y < MAXROWS; y++)
{
for(int x=0; x< MAXCOLS; x++)
{
startPos.x = x;
startPos.y = y;
tmpseq = getSequence(grid, startPos);
if (maxseq.size > tmpseq.size)
{
maxseq = tmpseq;
}
}
}
cout << "The longest increasing sequence in the grid is:\n\n";
printArray(maxseq.list, maxseq.size);
cout << "\nLength: " << maxseq.size << endl;