Spiral Matrix – clockwise and counter-clockwise

Written by Mushfiq Mammadov

Print matrix elements as spiral order from beginning the center element. It should be as the following picture:



The following video is short review about how the above code works:

You can also test it via this link.


Github link:


But for loop was used many times in the above code. So I optimized and rewrote code again:



Then it is added two features:

  1. If center element is more than 1 so you can choose it;
  2. All elements of matrix was included to spiral order. 

The last version of code after all updates:



Github link: 


About the author

Mushfiq Mammadov


  • Hello,
    I tried this code on the java platform in my laptop. the very last output doesn’t match with the code…. I mean to say as illustrated in the example just before this particular code. It should be clockwise as per the example but it prints in the anticlockwise pattern.
    Hope you would look into this. 🙂

    • You are right. The following code line
      private static final boolean isClockwise = false;
      should be
      private static final boolean isClockwise = true;

      I fixed it. Thanks for your response.

Leave a Comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.