【问题标题】:2d array rows and cols Backwards ? -Java二维数组行和列向后? -Java
【发布时间】:2015-05-20 05:02:27
【问题描述】:

考虑到这一点

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。我错过了什么?

【问题讨论】:

    标签: java arrays initializer-list


    【解决方案1】:

    当这样做时:

    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]

    翻转输入矩阵

    改变外部循环

    【讨论】:

      猜你喜欢
      • 2015-11-29
      • 1970-01-01
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多