Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

java - How do you rotate a 2D array 90 degrees without using a storage array?

I was instructed not to use a storage array to complete this task. Basically, we have to create a function that rotates the contents of a 2d array 90 degrees.

So if I start off with this array:

int[][] array = {{1,2,3}, {4,5,6}, {7,8,9}};

The function should return an array like this:

{{7,4,1}, {8,5,2}, {9,6,3}}

Again we are not allowed to use a created array within the function for storage. Is it even possible to accomplish this without a storage array?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can rotate/transpose the array by swapping the upper half with the lower half one by one:

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        int[][] array = new int[][] {
            new int[] { 1, 2, 3},
            new int[] { 4, 5, 6},
            new int[] { 7, 8, 9},
        };

        for (int row = 0; row < 3; row++) {
            for (int col = 0; col < row; col++) {
                int t = array[row][col];
                array[row][col] = array[col][row];
                array[col][row] = t;
            }
        }

        for (int row = 0; row < 3; row++) {
            System.out.println(Arrays.toString(array[row]));
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...