A second type of matrix transformation problem involves swapping matrix elements in different ways. One example is matrix transpose, which merely involves swapping element A[i][j] with element A[j][i]. A much more interesting example involves matrix rotation, e.g., the “rotate image” problem, which asks us to rotate a matrix by 90 degrees (clockwise or counterclockwise). This rotation problem can be solved through layer-level traversal. But different from the “layer rotation” problem discussed in “matrix transformation (1)“, the relative positions of elements at different layers are fixed in the “rotate image” problem. The following solution is from CTCI v6 page 203. The trick is to introduce 3 additional variables: “first” (start of a row or column), “last” (end of a row or column), and “offset” (index relative to the start).

Leave a Reply

Your email address will not be published. Required fields are marked *