我正在研究俄罗斯方块AI,我正在寻找一种翻转4乘4多维数组的方法。我看了一遍,我能找到的最多是旋转,这在我的情况下不起作用。 从
o o o o
o x x o
o x o o
o x o o
到
o x o o
o x o o
o x x o
o o o o
答案 0 :(得分:3)
我不知道您需要翻转哪个尺寸,但这是其中之一...请注意,此方法会破坏原始阵列!你并没有把你的需求弄清楚。
那就是说,这是一个解决方案
public static void main(String args[]) {
Integer[][] myArray = {{1, 3, 5, 7},{2,4,6,8},{10,20,30,40},{50,60,70,80}};
// Before flipping
printArray(myArray);
System.out.println();
// Flip
flipInPlace(myArray);
// After flipping
printArray(myArray);
}
public static void printArray(Object[][] theArray) {
for(int i = 0; i < theArray.length; i++) {
for(int j = 0; j < theArray[i].length; j++) {
System.out.print(theArray[i][j]);
System.out.print(",");
}
System.out.println();
}
}
// *** THIS IS THE METHOD YOU CARE ABOUT ***
public static void flipInPlace(Object[][] theArray) {
for(int i = 0; i < (theArray.length / 2); i++) {
Object[] temp = theArray[i];
theArray[i] = theArray[theArray.length - i - 1];
theArray[theArray.length - i - 1] = temp;
}
}
产地:
1,3,5,7,
2,4,6,8,
10,20,30,40,
50,60,70,80,
50,60,70,80,
10,20,30,40,
2,4,6,8,
1,3,5,7,
答案 1 :(得分:0)
我不知道翻转意味着什么,但根据您的示例,结果可以通过
来实现temp = array[0];
array[0] = array[3];
array[3] = temp;
temp = array[1];
array[1] = array[2];
array[2] = temp;
答案 2 :(得分:0)
你可以编写类似的代码(伪代码,我已经很久没做过Java了,但是你明白了)
function flipGridVertically(gridToFlip){
Array gridToReturn;
//start from the bottom row (gridToFlip.size is the vertical size of the grid)
//size is the horizontal size of the grid.
for (counter=gridToFlip.size-1; counter>0; counter--)
//start the second loop from the top
for (counter2=0;counter2<gridToFlip.size;counter2++)
gridToReturn[counter2] = gridToFlip[counter];
return gridToReturn;
}