0

我完全不知道如何解决这个问题,但我在 Java 中为 AI 寻路系统使用了一个数组,我需要对这些值进行排序。这是我正在生成的数组:

int[][] paths = new int[Settings.GAME_COLS][Settings.GAME_ROWS]; // Just creating an Array that has room for every tile in the Game, so the Array can be used like this: paths[x][y]
int tempF = 0;

tempF = Math.abs(14 + (((aiX + 1) - playerX) + ((aiY - 1) - playerY)));
paths[aiX + 1][aiY - 1] = tempF;
tempF = Math.abs(14 + (((aiX + 1) - playerX) + ((aiY + 1) - playerY)));
paths[aiX + 1][aiY + 1] = tempF;
tempF = Math.abs(14 + (((aiX - 1) - playerX) + ((aiY + 1) - playerY)));
paths[aiX - 1][aiY + 1] = tempF;
tempF = Math.abs(14 + (((aiX - 1) - playerX) + ((aiY - 1) - playerY)));
paths[aiX - 1][aiY - 1] = tempF;
tempF = Math.abs(10 + (((aiX + 1) - playerX) + (aiY - playerY)));
paths[aiX + 1][aiY    ] = tempF;
tempF = Math.abs(10 + (((aiX - 1) - playerX) + (aiY - playerY)));
paths[aiX - 1][aiY    ] = tempF;
tempF = Math.abs(10 + ((aiX - playerX) + ((aiY + 1) - playerY)));
paths[aiX    ][aiY + 1] = tempF;
tempF = Math.abs(10 + ((aiX - playerX) + ((aiY - 1) - playerY)));
paths[aiX    ][aiY - 1] = tempF;

这一切都可以完美地找到并生成包含所需信息的数组,但我需要根据添加到数组中的“tempF”值对数组进行排序。是否有捷径可寻?

4

2 回答 2

2

多维数组只不过是一组数组,因此您可以使用常规 Arrays.sort方法对数组数组进行就地排序。

于 2012-09-04T18:28:27.343 回答
0
for(int k=0;k<N;k++)  // loop for relaxation between row-column sorts
{
    for(int i=0;i<N;i++)
    {
       //row-wise sortings(for all rows)
       Arrays.sort(your_array[i]); 
    }

      for ( int c = 0 ; c < N ; c++ )
      {
         for( int d = 0 ; d < N ; d++ )               
         transposed_your_array[d][c] = your_array[c][d];         
      }  

    for(int i=0;i<N;i++)
    {
       //column-wise sortings(for all columns)
       Arrays.sort(transposed_your_array[i]);
    }

    for ( int c = 0 ; c < N ; c++ )
    {
        for( int d = 0 ; d < N ; d++ )               
        your_array[d][c] = transposed_your_array[c][d];         
    }  //getting original array from transpose


}
//There are actually N*N 1-D(N-element)arrays in a N x N matrix
//Every sort on a row-array alters the bounding column-arrays too(N of them)


//a worked example:
//8  3  8
//11 8  3
//6  12 6

//output:
//  this(0,0) is smallest element
//  ^
//  |
//  3  6  8
//  3  8  11
//  6  8  12 ---->this (2,2) is biggest element

//some other examples:
//10 8 8 
//11 4 7 
//9 5 3 
//
//3 5 9 ----> this 9 could be in place of 8 down there but this 
//4 7 10      program sorts rows first then sorts columns
//8 8 11      you can interleave them for better resolution sort(slower)
于 2012-09-04T18:38:13.150 回答