简体   繁体   中英

Array index out of bounds - 2d to 1d

I am working with the algs4 8-puzzle program presented by Princeton. I am getting an array index out of bounds exception in my second for loop. Does anyone see the issue that is throwing this exception? My board class + relevant method looks like this:

public class Board {
 private final int[][] blocks;
 private final int N;

 // construct a board from an N-by-N array of blocks
 // (where blocks[i][j] = block in row i, column j)
    public Board(int[][] blocks){
     N = blocks.length;
     this.blocks = new int[N][];
     for (int i=0; i<N; i++){
      this.blocks[i] = Arrays.copyOf(blocks[i], N);
     }
    }

    // board dimension N
    public int dimension(){
     return this.N;
    }

   //is the board solvable? 
   public boolean isSolvable(){
      int inversions = 0; 
      List<Integer> convert = new ArrayList<>(); // convert 2d to 1d 
      for (int i = 0; i < blocks.length; i++){
          for (int j = 0; j < blocks[i].length; j++){
              convert.add(blocks[i][j]);
          }
      }
      for (int i = 0; i < blocks.length; i++){ //counts the number of inversions 
          if (convert.get(i) < convert.get(i-1)){ //ARRAYINDEXOUTOFBOUNDS -1
              inversions++; 
          }
      }
      if (inversions % 2 == 0){
          return true; //even 
      }
      return false; //odd 
  }

convert.get(i-1) is out of bounds when i==0.

You should probably change the start index of your loop :

  for (int i = 1; i < blocks.length; i++){ //counts the number of inversions 
      if (convert.get(i) < convert.get(i-1)){ 
          inversions++; 
      }
  }

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