This type of problems are quite different from those discussed in “changing matrix elements” in the sense that the traversal can no longer be implemented using a simple nested loop that goes through row index and column index in order. One example is the “matrix layer rotation” problem, in which each layer of the matrix is rotated counterclockwise by a certain amount, which is different for different layers. In my solution in the following, I first traverse the matrix layer by layer from outside towards center and store the elements in each layer into a separate list. After this re-arrangement of the matrix elements, the elements in a rotated layer can be accessed through indexing as discussed in “querying the rotated array“. I then reconstruct the rotated matrix using the layers with the rotated index. During all those operations, it is important to fix a reference point and I used the upper-left corner, row = 0 and column = 0, as the reference.

A closely related problem is the “spiral matrix” problem, in which we need to traverse the matrix in spiral order. For this problem, it is important to check for corner cases (matrix that is very elongated along horizontal or vertical direction). My solution is the following.

There is also a problem that asks us to reconstruct a matrix from its spiral order traversal (the “spiral matrix II” problem). My solution is the following.

Leave a Reply

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