2d方形阵列中的翻转值
问题描述:
有没有办法让我只用一个嵌套for循环执行第一个方法,而没有第一个for循环一些值没有翻转,因为你基本上正在执行逆x,y - - > y,x并翻转x = y(因为0,0是左上角)为什么我的嵌套for循环不能自行工作?2d方形阵列中的翻转值
/**
* <pre>
* ~~~~~~ BONUS ~~~~~~ EXTRA CREDIT ~~~~~~
* transpose grid (similar to arrayReverse)
* (i.e. reflect over its main diagonal
* (which runs top-left to bottom-right)
* you MUST call the swap helper method
* but you man NOT create a second array for storage
* example:
* 1 2 3 1 4 7
* 4 5 6 would become 2 5 8
* 7 8 9 3 6 9
* </pre>
*/
public static void gridTranspose() {
if (gridIsSquare() == true) {
for (int r = 0; r < grid.length/2 + 1; r++) {
gridSwap(0, r, r, 0);
}
for (int r = 0; r < grid.length/2 + 1; r++) {
for (int c = 0; c < grid[0].length; c++) {
gridSwap(r, c, c, r);
}
}
}
}
/**
* <pre>
* ~~~~~~ BONUS ~~~~~~ EXTRA CREDIT ~~~~~~ swap the values at grid[r1][c1]
* and grid[r2][c2] you may use use an int temp as a temporary variable
*/
public static void gridSwap(int r1, int c1, int r2, int c2) {
int temp = grid[r1][c1];
grid[r1][c1] = grid[r2][c2];
grid[r2][c2] = temp;
}
答
下面是代码只做第二循环
public static void gridTranspose() {
if (gridIsSquare() == true) {
for (int r = 0; r < grid.length/2 + 1; r++) {
for (int c = r+1; c < grid[0].length; c++) {
gridSwap(r, c, c, r);
}
}
}
}
您的代码看起来不错。什么是问题? –
我只想知道是否有办法用on打开我的第一个方法; y一个嵌套循环并消除循环的第一个方法。 – MickDom