{"id":3509,"date":"2017-12-31T17:48:47","date_gmt":"2017-12-31T12:18:47","guid":{"rendered":"http:\/\/theoryofprogramming.azurewebsites.net\/?p=3509"},"modified":"2017-12-31T17:48:47","modified_gmt":"2017-12-31T12:18:47","slug":"print-matrix-in-spiral-order","status":"publish","type":"post","link":"https:\/\/theoryofcoding.com\/index.php\/2017\/12\/31\/print-matrix-in-spiral-order\/","title":{"rendered":"Print matrix in spiral order"},"content":{"rendered":"<p><strong>Problem statement<\/strong> &#8211; Given a 2D array (or matrix) of N rows and M columns, print it in a spiral order. Example, for the below matrix &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nint&#x5B;] arr = {\n                {1, 2, 3},\n                {4, 5, 6},\n                {7, 8, 9},\n            };\n<\/pre>\n<p>The output is &#8211;<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n1 2 3 6 9 8 7 4 5\n<\/pre>\n<p><strong>Solution<\/strong> &#8211; When an interviewer asks you this question, he\/she is just testing your implementation skills. This question isn&#8217;t tough because it doesn&#8217;t have any corner cases, but it is quite tough to solve if you start over thinking.<\/p>\n<p>Let us label the rows\/columns which we must print &#8211;<\/p>\n<p><a href=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2017\/12\/spiral-1.jpg?ssl=1\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-3512\" src=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2017\/12\/spiral-1.jpg?resize=444%2C445&#038;ssl=1\" alt=\"Print matrix in spiral order Theory of Programming\" width=\"444\" height=\"445\" srcset=\"https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2017\/12\/spiral-1.jpg?w=444&amp;ssl=1 444w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2017\/12\/spiral-1.jpg?resize=300%2C300&amp;ssl=1 300w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2017\/12\/spiral-1.jpg?resize=150%2C150&amp;ssl=1 150w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2017\/12\/spiral-1.jpg?resize=230%2C231&amp;ssl=1 230w, https:\/\/i0.wp.com\/theoryofcoding.com\/wp-content\/uploads\/2017\/12\/spiral-1.jpg?resize=350%2C351&amp;ssl=1 350w\" sizes=\"auto, (max-width: 444px) 100vw, 444px\" data-recalc-dims=\"1\" \/><\/a>So, our top-most row is <em>top<\/em>, bottom-most row is <em>bottom<\/em>, left-most column is <em>left<\/em> and right-most column is <em>right<\/em>. As we keep printing elements of the matrix, we will bring them closer to each other. Initially &#8211;<\/p>\n<ul>\n<li><em>top<\/em> = 0<\/li>\n<li><em>right<\/em> = M &#8211; 1<\/li>\n<li><em>bottom<\/em>\u00a0 = N &#8211; 1<\/li>\n<li><em>left<\/em> = 0<\/li>\n<\/ul>\n<p>As per the arrow indication, in our <em>top<\/em> row, we will print elements from left to right. So the loop to print it will look something like &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nfor (int i = left; i &lt;= right; ++i) {\n    print arr&#x5B;top]&#x5B;i];\n}\n\n++top;\n<\/pre>\n<p>As you have noticed, the <em>++top<\/em> is to bring it towards the center. Similarly, for printing the <em>right<\/em> column &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nfor (int i = top; i &lt;= bottom; ++i) {\n    print arr&#x5B;i]&#x5B;right];\n}\n\n--right;\n<\/pre>\n<p>Similarly, for printing the <em>bottom<\/em> row &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nfor (int i = right; i &gt;= left; --i) {\n    print arr&#x5B;bottom]&#x5B;i];\n}\n\n--bottom;\n<\/pre>\n<p>Similarly, for printing the <em>left<\/em> column &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nfor (int i = bottom; i &gt;= top; --i) {\n    print arr&#x5B;i]&#x5B;left];\n}\n\n++left;\n<\/pre>\n<p>Now all that&#8217;s left is to execute this printing in a proper order. We could have a control variable <em>dir<\/em>, which denotes the direction. If &#8211;<\/p>\n<ul>\n<li><em>dir<\/em> == 1, print <em>top<\/em> row<\/li>\n<li><em>dir<\/em> == 2, print <em>right<\/em> column<\/li>\n<li><em>dir<\/em> == 3, print <em>bottom<\/em> row<\/li>\n<li><em>dir<\/em> == 4, print <em>left<\/em> column<\/li>\n<\/ul>\n<p>We must keep rotating the value of <em>dir<\/em> between 1, 2, 3, 4 as long as <em>top\u00a0\u2264 bottom<\/em> and <em>left \u2264 right<\/em>. If you have understood the logic, you should be able to write the code easily. If you didn&#8217;t just go through the explanation once more, it is can be tricky \ud83d\ude1b<\/p>\n<p><strong>Code<\/strong> &#8211;<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic static void printInSpiralOrder(final int&#x5B;]&#x5B;] arr) {\n    if (arr.length == 0 || arr&#x5B;0].length == 0) {\n        return;\n    }\n\n    int top = 0, bottom = arr.length - 1, left = 0, right = arr&#x5B;0].length - 1;\n    int dir = 1;\n\n    while (top &lt;= bottom &amp;&amp; left &lt;= right) {\n        if (dir == 1) {    \/\/ left-right\n            for (int i = left; i &lt;= right; ++i) {\n                System.out.print(arr&#x5B;top]&#x5B;i] + &quot; &quot;);\n            }\n\n            ++top;\n            dir = 2;\n        } else if (dir == 2) {     \/\/ top-bottom\n            for (int i = top; i &lt;= bottom; ++i) {\n                System.out.print(arr&#x5B;i]&#x5B;right] + &quot; &quot;);\n            }\n\n            --right;\n            dir = 3;\n        } else if (dir == 3) {     \/\/ right-left\n            for (int i = right; i &gt;= left; --i) {\n                System.out.print(arr&#x5B;bottom]&#x5B;i] + &quot; &quot;);\n            }\n\n            --bottom;\n            dir = 4;\n        } else if (dir == 4) {     \/\/ bottom-up\n            for (int i = bottom; i &gt;= top; --i) {\n                System.out.print(arr&#x5B;i]&#x5B;left] + &quot; &quot;);\n            }\n\n            ++left;\n            dir = 1;\n        }\n    }\n}\n<\/pre>\n<p>Keep practicing! Happy Coding! \ud83d\ude00<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Problem statement &#8211; Given a 2D array (or matrix) of N rows and M columns, print it in a spiral order. Example, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[16],"tags":[22,61],"class_list":["post-3509","post","type-post","status-publish","format-standard","hentry","category-array-interview-questions","tag-arrays-interview-questions","tag-interview-questions"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts\/3509","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/comments?post=3509"}],"version-history":[{"count":0,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/posts\/3509\/revisions"}],"wp:attachment":[{"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/media?parent=3509"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/categories?post=3509"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/theoryofcoding.com\/index.php\/wp-json\/wp\/v2\/tags?post=3509"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}