有没有办法让我只用一个嵌套for循环来做第一个方法,没有第一个for循环,一些值没有翻转,因为你基本上做了逆x,y - > y,x和翻转x = y(因为0,0是左上角)为什么单独赢得嵌套for循环工作?
/**
* <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;
}
答案 0 :(得分:0)
以下是仅执行第二个循环的代码
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);
}
}
}
}