0 ms 2-step C language solution, simple idea.


  • 2
    For instance:
    1 2 3
    4 5 6
    7 8 9
    step 1 is swap head and tail element in every row, than swap ++head and --tail...until head meet tail.
    3 2 1
    6 5 4
    9 8 7
    step 2 is swap elements based on axis [1, 5, 9].
    7 4 1
    8 5 2
    9 6 3
    

    Here is the code:

    void rotate(int** ma, int rs, int cs) 
    {
        if (rs - cs)
    		return;
    	const int ns = rs;
    
    	int i, j, k;
    	int t;
    	int dis;
    	//step1
    	for (i = 0; i < ns; ++i)
    	{
    		for (j = 0, k = ns - 1; j < k; ++j, --k)
    		{
    			t = ma[i][j];
    			ma[i][j] = ma[i][k];
    			ma[i][k] = t;
    		}
    	}
    	//step2
    	for (i = 0; i < ns-1; ++i)
    	{
    		for (j = 0; j < ns - 1 - i; ++j)
    		{
    			dis = ns - 1 - i - j;
    			t = ma[i][j];
    			ma[i][j] = ma[i + dis][j + dis];
    			ma[i + dis][j + dis] = t;
    		}
    	}
    	return;    
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.