I am currently working on a 15 puzzle programming assignment. My question here is about how I would go about swapping the empty tile with an adjacent tile.
So, for example, let's go with the initial setup board.
I have:
int originalBoard[4][4] = {
{1 , 2, 3, 4},
{5 , 6, 7, 8},
{9 ,10,11,12},
{13,14,15, 0}};
void locateEmptyTile(int& blankRow, int& blankColumn, int originalBoard[4][4])
{
for (int row = 0; row < 4; row++)
{
for (int col = 0; col < 4; col++)
{
if (originalBoard[row][col] == 0)
{
blankRow = row;
blankColumn = col;
}
}
}
}
void move(int& blankRow, int& blankColumn, int originalBoard[4][4])
{
}
main
int blankRow
int blankColumn
locateEmptyTile
move
A basic swap concept (pre-C++11) is hold a temporary variable. Simply...
template<typename T, typename U>
void swap(T& lhs, U& rhs) {
T t = lhs;
lhs = rhs;
rhs = t;
}
So, you don't need to reference blankRow
and blankCol
, you just need to reference the values on the grid. Lets say that you want to swap what you know is blank positioned at (2, 1)
with (2, 2)
...
swap(originalBoard[2][1], originalBoard[2][2]);
... will swap the values within originalBoard
.
If you are using C++11 or later, just use std::swap()
to swap positions. That's exactly what it does.
If you would like originalBoard
to be immutable an result in a totally different board, just copy it first before applying the switch.