HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Rotation of a 2D array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayrotationstackoverflow

Problem

The first line will contain numbers m (number of rows), n (number of columns), and b (number of rotations to be performed).

Suppose I have following 4X4 matrix:

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16


and b = 1,the output must be:

2 3 4 8
1 7 11 12
5 6 10 16
9 13 14 15


The problem I am facing is 3 test case are timing out and 9 test case successfully passed. Can somebody suggest a way or help me with optimizing my code?

Here is the link to the question.

I need a way to figure out how to minimize b, because some rotations will be useless as it will result in giving us the original array.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class So {
    private static BufferedReader br;
    private static int n,m,b;
    private static int [][]arr;    
    public static void main(String[] args)throws IOException {        
        int i,j;
        br=new BufferedReader(new InputStreamReader(System.in));
        String []str;
        str=br.readLine().split(" ");
        m=Integer.parseInt(str[0]);
        n=Integer.parseInt(str[1]);
        b=Integer.parseInt(str[2]);
        arr=new int[m][n];
        for(i=0;i=sr+1;--i)
        {
            arr[i][c-1]=prev;
            prev=res;
            res=arr[i-1][c-1];
        }
        for(i=c-1;i>=sc+1;--i)
        {
            arr[sr][i]=prev;
            prev=res;
            res=arr[sr][i-1];
        } 
        arr[sr][sc]=prev;
        sr++;sc++;r--;c--;
    }
    }
 }

Solution

Reduce the number of rotations

For each "ring" you rotate, the number of rotations you can do before you reach the original position again is: \$2*(rows + columns) - 4\$, where rows and columns are the number of rows and columns for the ring. So you can reduce the number of rotations like this:

sizeOfRing = 2*(r-sr + c-sc) - 4;
rotationsForThisRing = totalRotations % sizeOfRing;


You will of course need to modify your program to use a variable number of rotations per ring.

Code Snippets

sizeOfRing = 2*(r-sr + c-sc) - 4;
rotationsForThisRing = totalRotations % sizeOfRing;

Context

StackExchange Code Review Q#105768, answer score: 2

Revisions (0)

No revisions yet.