我如何在二维数组中移动空白 space ?

How would I move a blank space in a 2d array?

我正在开发一款滑块益智游戏,但不确定如何在阵列周围移动“空白”。这个谜题会像这样但是随机的。每种方法都有一个先决条件,表明它是否可以移动某个方向。

- 2 3
4 5 6
7 8 9
   // Modifies the puzzle by moving the blank up
   // pre: canMoveUp()
   public void up() {
      
   }

   // Modifies the puzzle by moving the blank down
   // pre: canMoveDown()
   public void down() {
      
   }

   // Modifies the puzzle by moving the blank left
   // pre: canMoveLeft()
   public void left() {
      
   }

   // Modifies the puzzle by moving the blank right
   // pre: canMoveRight()
   public void right() {
      
   }

这是一个如何实现 right() 的示例,其余方法将非常相似。正如您的评论所暗示的那样,我假设此举的合法性已经得到验证。

/*
represent the board in a 2-dimensional array with the following coordinate system
  x --->
y
|
\/
*/

int x, y = 0; // keeping track of the blank position

int[][] board = ... // initialize the board as needed (sequentially? randomly?), assume -1 represents the blank space

public void right() { // move the blank in the positive x direction
    // get the value currently in the position that the blank must move to, as it will need to be swapped
    int tmp = board[x + 1][y]; 
    board[x + 1][y] = -1; // move the blank here
    board[x][y] = tmp; // complete the swap
    x = x + 1; // the new x position of the blank needs to be updated
}