cs50 game of fiteen move does not move am quite stuck

Thank you both for your help. I have tried to change my code but it still does not work. If you can give me one or two more hints, would be grateful. Thanks.

``````bool move(int tile)
{
if (tile > d*d-1 || tile <1)
{
return false;
}

for (int i = 0; i < d ; i++)
{
for ( int j = 0; j < d; j ++)
{
if (board[i][j] == tile)
{
if(board[i+1][j] == 0)
{
//swap
int temp = board[i][j];
board[i][j] = board[i+1][j];
board[i+1][j] = temp;
return true;
}
else if (board[i-1][j] == 0)
{
int temp = board[i][j];
board[i][j] = board[i-1][j];
board[i-1][j] = temp;
return true;
}
else if (board[i][j+1] == 0)
{
int temp = board[i][j];
board[i][j] = board[i][j+1];
board[i][j+1] = temp;
return true;
}
else if (board[i][j-1] == 0)
{
int temp = board[i][j];
board[i][j] = board[i][j-1];
board[i][j-1] = temp;
return true;
}
}
}
}
return false;
}
``````

The problem here is that when tile is on the edge of the board, as it is at the start, the code is looking off the edge of the board to find the blank tile. Let's work an example to illustrate.

Say that d=3 and the game is just starting. Now say that we want to swap tile 1, which is to the left of the blank or 0 tile. As the for loops execute, it will eventually find 1 at board[2][1].

Now, the if/else if sequence will execute. In this case, the following will execute and be found true:

``````        if(board[i+1][j] == 0)
``````

At this point, i=2, so i+1=3. This is off the edge of the board, or outside the active area of the board array. The code following will execute because even though d=3 and i should never be greater than 2, the actual array is 9x9. The values outside of the 3x3 area will all likely be 0. So, when it does the compare, it will perform the swap, moving the tile off the active board into the unused part of the array and pulling an extra 0 into the active area of the board array. By similar logic, i or j could be -1. This generally won't result in an error, but it will generate unpredictable results, depending on what is in adjacent memory.

The code needs to make sure that when its looking at i+1, i-1, j+1 or j-1, that it is only looking at the active area of the board.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

• thank you very much – stephen Ong Jul 29 '17 at 14:56