简体   繁体   中英

2d array rows and cols Backwards ? -Java

Considering this

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();
}

when passing goal to the constructor i would expect the top row to read 1,5,9,13 not 1,2,3,4 which it currently does. what am i missing?

When doing this:

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

The array is populated along the j axis first, so you get 1,2,3,4 because that are the values at position 0 of the input. To get it the way you want, either assign grid[j][i] instead of [i][j]

or

turn around the input matrix

or

change the outer loops

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM