2d数组行和cols向后? -Java

时间:2015-05-20 05:02:27

标签: java arrays initializer-list

考虑到这个

private int[][] goal = {{1,5,9,13}, {2,6,10,14}, {3,7,11,15},{4,8,12,0}};

public FifteenPuzzle1 (int[][] initialGrid) {

    if (initialGrid == null) 
        throw new NullPointerException("null grid");
    if (initialGrid.length != size) 
        throw new IllegalArgumentException("Grid does not have " + size + " rows");

     for (int i = 0; i < size; i++) {
         if (initialGrid[i] == null)
             throw new NullPointerException("null row");
         else if (initialGrid[i].length != size)
             throw new IllegalArgumentException("Grid is not square");
      }

      grid = initialGrid;
      boolean[] found = new boolean[size * size];

      for (int i = 0; i < size; i++) {
          for (int j = 0; j < size; j++) {
             if (grid[i][j] < 0)
                throw new IllegalArgumentException("Negative square found: " + grid[i][j]);
             else if (grid[i][j] > size * size - 1)
                throw new IllegalArgumentException("Overflow square found: " + grid[i][j]);
             else if (found[grid[i][j]])
                throw new IllegalArgumentException("Grid has multiple " + grid[i][j] + "s");
             else {
                 found[grid[i][j]] = true;
                     if (grid[i][j] == 0) {
                         xspace = i; yspace = j;
                     }
              }
          }
      }

      sc = new SimpleCanvas("Fifteen Puzzle", gridsize, gridsize, bgColor);
      sc.addMouseListener(this);
      drawGrid();
}

当将目标传递给构造函数时,我希望顶行读取1,5,9,13 它目前没有1,2,3,4。我错过了什么?

1 个答案:

答案 0 :(得分:0)

这样做时:

for (int i = 0; i < x; i++) {
  for (int j = 0; j < y; j++) {
  ...
  }
}

首先沿j轴填充数组,因此得到1,2,3,4,因为这是输入位置0的值。要按照您想要的方式获取,请指定grid[j][i]而不是[i][j]

转动输入矩阵

更改外循环