Wednesday, April 30, 2014

Steps to solve a technical question in an interview: Matrix Rotation

Step one: ask whether clockwise or counterclockwise, the degree to rotate, whether the matrix is a square matrix or not.

Step two: talk with inteviewers about the solution.

Step three: write code. it's OK if there are bugs, make sure give test cases to find out them.

Thought: rotate the matrix layer by layer. On each layer, first rotate the four corners, then rotate next one till the last. first=layer and last = n-layer-1 (excluded)

void matrixRotation(int [][] matrix, int n){
    
    for(int layer =0; layer < n/2; layer++){
   //if n is odd,the most inner element doesn't need to be rotate
        int first = layer;
        int last = n-layer -1;
        for(int i=first; i<last; i++){
            int offset = i-first;
            //first save the top value
            int top = matrix[first][i];
            //left-->top
            matrix[first][i] = matrix[last-offset][first];
            //bottom-->left
            matrix[last-offset][first]=matrix[last][last-offset];
            //right-->bottom
            matrix[last][last-offset]= matrix[i][last];
            //top-->right
            matrix[i][last] = top;
        }
    }
}

No comments:

Post a Comment