Rotation of a 2D array 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&lt;m;++i)
        {
            str=br.readLine().split(" ");
            for(j=0;j&lt;n;++j)
             arr[i][j]=Integer.parseInt(str[j]);
        }
        i=0;
        while(i++&lt;b)        
         rotate();       
        for(i=0;i&lt;m;++i)
        {
            for(j=0;j&lt;n;++j)
             System.out.print(arr[i][j]+" ");             
            System.out.println();
        }
    }
    public static void rotate()
    {
        int sr=0,sc=0,r=m,c=n,i,j,prev,res;
        while(sr&lt;=r-2&amp;&amp;sc&lt;=c-2)
        {prev=arr[sr][sc];        
        res=arr[sr+1][sc];
        for(i=sr+1;i&lt;=r-2;++i)
        {
            arr[i][sc]=prev;
            prev=res;
            res=arr[i+1][sc];
        }
        for(i=sc;i&lt;=c-2;++i)
        {
            arr[r-1][i]=prev;
            prev=res;
            res=arr[r-1][i+1];
        }
        for(i=r-1;i&gt;=sr+1;--i)
        {
            arr[i][c-1]=prev;
            prev=res;
            res=arr[i-1][c-1];
        }
        for(i=c-1;i&gt;=sc+1;--i)
        {
            arr[sr][i]=prev;
            prev=res;
            res=arr[sr][i-1];
        } 
        arr[sr][sc]=prev;
        sr++;sc++;r--;c--;
    }
    }
 }
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.