{"id":16684,"date":"2023-06-05T10:12:20","date_gmt":"2023-06-05T10:12:20","guid":{"rendered":"https:\/\/www.prepbytes.com\/blog\/?p=16684"},"modified":"2023-06-05T10:20:30","modified_gmt":"2023-06-05T10:20:30","slug":"spiral-traversal-of-a-matrix-in-python","status":"publish","type":"post","link":"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/","title":{"rendered":"Spiral Traversal Of A Matrix In Python"},"content":{"rendered":"<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1685958822756-Spiral%20traversal%20of%20a%20matrix%20in%20Python.jpg\" alt=\"\" \/><\/p>\n<p>The traversal of a matrix is a common operation in many programming tasks. The spiral traversal is a specific traversal pattern in which the elements of the matrix are visited in a spiral-like order, beginning at the top-left corner and moving clockwise until all elements are visited. In this article, we will look at various algorithms and provide Python code examples for the spiral traversal of a matrix.<\/p>\n<p>What is a matrix spiral traversal?<br \/>\nSpiral traversal of a matrix is a method of visiting the elements of a two-dimensional matrix in a spiral-like order, beginning at the top-left corner and moving clockwise until all elements have been visited.<\/p>\n<p>Example of spiral matrix in Python:<br \/>\n<img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1685958864650-1-01%20%289%29.png\" alt=\"\" \/><\/p>\n<p>The preceding example shows how we can traverse the matrix in a spiral fashion. So, in order to solve this problem, we will primarily discuss four approaches: <\/p>\n<ol>\n<li>Iterative procedure<\/li>\n<li>Recursive strategy<\/li>\n<li>Using the DFS method<\/li>\n<li>Using a deque<\/li>\n<\/ol>\n<h2>Method 1 : Iterative Approach to solve spiral traversal of a matrix in Python<\/h2>\n<ol>\n<li>To keep track of the spiral&#8217;s boundaries, initialize four variables: top, bottom, left, and right.<\/li>\n<li>Create an empty list,&#8217;result,&#8217; to hold the visited elements.<\/li>\n<li>Create a while loop that runs until &#8216;top = bottom&#8217; and &#8216;left = right&#8217;.<\/li>\n<li>Go through the top row from left to right, appending &#8216;result&#8217; to each element.<\/li>\n<li>Increase the value of &#8216;top&#8217; by one to exclude the top row from future iterations.<\/li>\n<li>Go down the right column from top to bottom, appending &#8216;result&#8217; to each element.<\/li>\n<li>Increase the value of &#8216;right&#8217; by one to exclude the right column from future iterations.<\/li>\n<li>Before proceeding, ensure that &#8216;top = bottom&#8217; and &#8216;left = right&#8217;.<\/li>\n<li>Go down the bottom row from right to left, appending &#8216;result&#8217; to each element.<\/li>\n<li>Increase the value of &#8216;bottom&#8217; by one to exclude the bottom row from future iterations.<\/li>\n<li>Traverse the left column from bottom to top, appending each element to <code>result<\/code>.<\/li>\n<li>Increase &#8216;left&#8217; by one to remove the left column from subsequent iterations.<\/li>\n<li>Display the result list.<\/li>\n<\/ol>\n<h3>Python code for the iterative approach:<\/h3>\n\t\t\t\t\t\t<style>\r\n\t\t\t\t\r\n\t\t\t\t\t#tab_container_16682 {\r\n\toverflow:hidden;\r\n\tdisplay:block;\r\n\twidth:100%;\r\n\tborder:0px solid #ddd;\r\n\tmargin-bottom:30px;\r\n\t}\r\n\r\n#tab_container_16682 .tab-content{\r\n\tpadding:20px;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n\tmargin-top: 0px;\r\n\tbackground-color:#ffffff !important;\r\n\tcolor: #000000 !important;\r\n\tfont-size:16px !important;\r\n\tfont-family: Open Sans !important;\r\n\t\r\n\t\tborder: 1px solid #e6e6e6 !important;\r\n\t}\r\n#tab_container_16682 .wpsm_nav-tabs {\r\n    border-bottom: 0px solid #ddd;\r\n}\r\n#tab_container_16682 .wpsm_nav-tabs > li.active > a, #tab_container_16682 .wpsm_nav-tabs > li.active > a:hover, #tab_container_16682 .wpsm_nav-tabs > li.active > a:focus {\r\n\tcolor: #000000 !important;\r\n\tcursor: default;\r\n\tbackground-color: #ffffff !important;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n}\r\n\r\n#tab_container_16682 .wpsm_nav-tabs > li > a {\r\n    margin-right: 0px !important; \r\n    line-height: 1.42857143 !important;\r\n    border: 1px solid #d5d5d5 !important;\r\n    border-radius: 0px 0px 0 0 !important; \r\n\tbackground-color: #e8e8e8 !important;\r\n\tcolor: #000000 !important;\r\n\tpadding: 15px 18px 15px 18px !important;\r\n\ttext-decoration: none !important;\r\n\tfont-size: 14px !important;\r\n\ttext-align:center !important;\r\n\tfont-family: Open Sans !important;\r\n}\r\n#tab_container_16682 .wpsm_nav-tabs > li > a:focus {\r\noutline: 0px !important;\r\n}\r\n\r\n#tab_container_16682 .wpsm_nav-tabs > li > a:before {\r\n\tdisplay:none !important;\r\n}\r\n#tab_container_16682 .wpsm_nav-tabs > li > a:after {\r\n\tdisplay:none !important ;\r\n}\r\n#tab_container_16682 .wpsm_nav-tabs > li{\r\npadding:0px !important ;\r\nmargin:0px;\r\n}\r\n\r\n#tab_container_16682 .wpsm_nav-tabs > li > a:hover , #tab_container_16682 .wpsm_nav-tabs > li > a:focus {\r\n    color: #000000 !important;\r\n    background-color: #e8e8e8 !important;\r\n\tborder: 1px solid #d5d5d5 !important;\r\n\t\r\n}\r\n#tab_container_16682 .wpsm_nav-tabs > li > a .fa{\r\n\r\nmargin-right:5px !important;\r\n\r\nmargin-left:5px !important;\r\n\r\n\r\n}\r\n\r\n\t\t#tab_container_16682 .wpsm_nav-tabs a{\r\n\t\t\tbackground-image: none;\r\n\t\t\tbackground-position: 0 0;\r\n\t\t\tbackground-repeat: repeat-x;\r\n\t\t}\r\n\t\t\t\r\n\r\n\r\n#tab_container_16682 .wpsm_nav-tabs > li {\r\n    float: left;\r\n    margin-bottom: -1px !important;\r\n\tmargin-right:0px !important; \r\n}\r\n\r\n\r\n#tab_container_16682 .tab-content{\r\noverflow:hidden !important;\r\n}\r\n\r\n\r\n@media (min-width: 769px) {\r\n\r\n\t#tab_container_16682 .wpsm_nav-tabs > li{\r\n\t\tfloat:left !important ;\r\n\t\t\t\tmargin-right:-1px !important;\r\n\t\t\t\t\t}\r\n\t#tab_container_16682 .wpsm_nav-tabs{\r\n\t\tfloat:none !important;\r\n\t\tmargin:0px !important;\r\n\t}\r\n\r\n\t#tab_container_16682 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_16682 .wpsm_nav{\r\n\t\t\t}\r\n\r\n}\r\n\r\n\r\n\r\n@media (max-width: 768px) {\r\n\t#tab_container_16682 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_16682 .wpsm_nav{\r\n\t\t\t}\r\n}\r\n\r\n\r\n\t.wpsm_nav-tabs li:before{\r\n\t\tdisplay:none !important;\r\n\t}\r\n\r\n\t@media (max-width: 768px) {\r\n\t\t\t\t\r\n\t\t\t\t.wpsm_nav-tabs{\r\n\t\t\tmargin-left:0px !important;\r\n\t\t\tmargin-right:0px !important; \r\n\t\t\t\r\n\t\t}\r\n\t\t\t\t#tab_container_16682 .wpsm_nav-tabs > li{\r\n\t\t\tfloat:none !important;\r\n\t\t}\r\n\t\t\t\r\n\t}\t\t\t\t<\/style>\r\n\t\t\t\t<div id=\"tab_container_16682\" >\r\n\t \r\n\t\t\t\t\t<ul class=\"wpsm_nav wpsm_nav-tabs\" role=\"tablist\" id=\"myTab_16682\">\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  class=\"active\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_16682_1\" aria-controls=\"tabs_desc_16682_1\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Python<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\t\t\t\t <\/ul>\r\n\r\n\t\t\t\t\t  <!-- Tab panes -->\r\n\t\t\t\t\t  <div class=\"tab-content\" id=\"tab-content_16682\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane  in active \" id=\"tabs_desc_16682_1\">\r\n\t\t\t\t\t\t\t\t<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">def spiral_traversal(matrix):\r\n    top = 0\r\n    bottom = len(matrix) - 1\r\n    left = 0\r\n    right = len(matrix[0]) - 1\r\n    result = []\r\n\r\n    while top &lt;= bottom and left &lt;= right:\r\n        for i in range(left, right + 1):\r\n            result.append(matrix[top][i])\r\n        top += 1\r\n        for i in range(top, bottom + 1):\r\n            result.append(matrix[i][right])\r\n        right -= 1\r\n\r\n        if top &lt;= bottom and left &lt;= right:\r\n           \r\n            for i in range(right, left - 1, -1):\r\n                result.append(matrix[bottom][i])\r\n            bottom -= 1\r\n\r\n            for i in range(bottom, top - 1, -1):\r\n                result.append(matrix[i][left])\r\n            left += 1\r\n    return result\r\n<\/pre>\r\n&nbsp;\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t <\/div>\r\n\t\t\t\t\t \r\n\t\t\t\t <\/div>\r\n <script>\r\n\t\tjQuery(function () {\r\n\t\t\tjQuery('#myTab_16682 a:first').tab('show')\r\n\t\t});\r\n\t\t\r\n\t\t\t\tjQuery(function(){\r\n\t\t\tvar b=\"fadeIn\";\r\n\t\t\tvar c;\r\n\t\t\tvar a;\r\n\t\t\td(jQuery(\"#myTab_16682 a\"),jQuery(\"#tab-content_16682\"));function d(e,f,g){\r\n\t\t\t\te.click(function(i){\r\n\t\t\t\t\ti.preventDefault();\r\n\t\t\t\t\tjQuery(this).tab(\"show\");\r\n\t\t\t\t\tvar h=jQuery(this).data(\"easein\");\r\n\t\t\t\t\tif(c){c.removeClass(a);}\r\n\t\t\t\t\tif(h){f.find(\"div.active\").addClass(\"animated \"+h);a=h;}\r\n\t\t\t\t\telse{if(g){f.find(\"div.active\").addClass(\"animated \"+g);a=g;}else{f.find(\"div.active\").addClass(\"animated \"+b);a=b;}}c=f.find(\"div.active\");\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\r\n\t\tfunction do_resize(){\r\n\r\n\t\t\tvar width=jQuery( '.tab-content .tab-pane iframe' ).width();\r\n\t\t\tvar height=jQuery( '.tab-content .tab-pane iframe' ).height();\r\n\r\n\t\t\tvar toggleSize = true;\r\n\t\t\tjQuery('iframe').animate({\r\n\t\t\t    width: toggleSize ? width : 640,\r\n\t\t\t    height: toggleSize ? height : 360\r\n\t\t\t  }, 250);\r\n\r\n\t\t\t  toggleSize = !toggleSize;\r\n\t\t}\r\n\r\n\r\n\t<\/script>\r\n\t\t\t\t\r\n\t\t\t\n<h2>Method 2: Recursive Approach to solve spiral traversal of a matrix in Python<\/h2>\n<ol>\n<li>Initialize four variables: <code>top<\/code>, <code>bottom<\/code>, <code>left<\/code>, and <code>right<\/code> to keep track of the boundaries of the spiral.<\/li>\n<li>Initialize an empty list, <code>result<\/code>, to store the visited elements.<\/li>\n<li>Define a recursive function, <code>spiral_traversal_recursive(matrix, top, bottom, left, right, result)<\/code>.<\/li>\n<li>Base case: If <code>top &gt; bottom<\/code> or <code>left &gt; right<\/code>, return.<\/li>\n<li>Traverse the top row from left to right, appending each element to <code>result<\/code>.<\/li>\n<li>Increment <code>top<\/code> by 1.<\/li>\n<li>Traverse the right column from top to bottom, appending each element to <code>result<\/code>.<\/li>\n<li>Decrement <code>right<\/code> by 1.<\/li>\n<li>Traverse the bottom row from right to left, appending each element to <code>result<\/code>.<\/li>\n<li>Decrement <code>bottom<\/code> by 1.<\/li>\n<li>Traverse the left column from bottom to top, appending each element to <code>result<\/code>.<\/li>\n<li>Increment <code>left<\/code> by 1.<\/li>\n<li>Recursively call `<\/li>\n<li>Call <code>spiral_traversal_recursive(matrix, top, bottom, left, right, result)<\/code> initially.<\/li>\n<li>Return the <code>result<\/code> list.<\/li>\n<\/ol>\n<h3>Python code for the recursive approach:<\/h3>\n\t\t\t\t\t\t<style>\r\n\t\t\t\t\r\n\t\t\t\t\t#tab_container_16686 {\r\n\toverflow:hidden;\r\n\tdisplay:block;\r\n\twidth:100%;\r\n\tborder:0px solid #ddd;\r\n\tmargin-bottom:30px;\r\n\t}\r\n\r\n#tab_container_16686 .tab-content{\r\n\tpadding:20px;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n\tmargin-top: 0px;\r\n\tbackground-color:#ffffff !important;\r\n\tcolor: #000000 !important;\r\n\tfont-size:16px !important;\r\n\tfont-family: Open Sans !important;\r\n\t\r\n\t\tborder: 1px solid #e6e6e6 !important;\r\n\t}\r\n#tab_container_16686 .wpsm_nav-tabs {\r\n    border-bottom: 0px solid #ddd;\r\n}\r\n#tab_container_16686 .wpsm_nav-tabs > li.active > a, #tab_container_16686 .wpsm_nav-tabs > li.active > a:hover, #tab_container_16686 .wpsm_nav-tabs > li.active > a:focus {\r\n\tcolor: #000000 !important;\r\n\tcursor: default;\r\n\tbackground-color: #ffffff !important;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n}\r\n\r\n#tab_container_16686 .wpsm_nav-tabs > li > a {\r\n    margin-right: 0px !important; \r\n    line-height: 1.42857143 !important;\r\n    border: 1px solid #d5d5d5 !important;\r\n    border-radius: 0px 0px 0 0 !important; \r\n\tbackground-color: #e8e8e8 !important;\r\n\tcolor: #000000 !important;\r\n\tpadding: 15px 18px 15px 18px !important;\r\n\ttext-decoration: none !important;\r\n\tfont-size: 14px !important;\r\n\ttext-align:center !important;\r\n\tfont-family: Open Sans !important;\r\n}\r\n#tab_container_16686 .wpsm_nav-tabs > li > a:focus {\r\noutline: 0px !important;\r\n}\r\n\r\n#tab_container_16686 .wpsm_nav-tabs > li > a:before {\r\n\tdisplay:none !important;\r\n}\r\n#tab_container_16686 .wpsm_nav-tabs > li > a:after {\r\n\tdisplay:none !important ;\r\n}\r\n#tab_container_16686 .wpsm_nav-tabs > li{\r\npadding:0px !important ;\r\nmargin:0px;\r\n}\r\n\r\n#tab_container_16686 .wpsm_nav-tabs > li > a:hover , #tab_container_16686 .wpsm_nav-tabs > li > a:focus {\r\n    color: #000000 !important;\r\n    background-color: #e8e8e8 !important;\r\n\tborder: 1px solid #d5d5d5 !important;\r\n\t\r\n}\r\n#tab_container_16686 .wpsm_nav-tabs > li > a .fa{\r\n\r\nmargin-right:5px !important;\r\n\r\nmargin-left:5px !important;\r\n\r\n\r\n}\r\n\r\n\t\t#tab_container_16686 .wpsm_nav-tabs a{\r\n\t\t\tbackground-image: none;\r\n\t\t\tbackground-position: 0 0;\r\n\t\t\tbackground-repeat: repeat-x;\r\n\t\t}\r\n\t\t\t\r\n\r\n\r\n#tab_container_16686 .wpsm_nav-tabs > li {\r\n    float: left;\r\n    margin-bottom: -1px !important;\r\n\tmargin-right:0px !important; \r\n}\r\n\r\n\r\n#tab_container_16686 .tab-content{\r\noverflow:hidden !important;\r\n}\r\n\r\n\r\n@media (min-width: 769px) {\r\n\r\n\t#tab_container_16686 .wpsm_nav-tabs > li{\r\n\t\tfloat:left !important ;\r\n\t\t\t\tmargin-right:-1px !important;\r\n\t\t\t\t\t}\r\n\t#tab_container_16686 .wpsm_nav-tabs{\r\n\t\tfloat:none !important;\r\n\t\tmargin:0px !important;\r\n\t}\r\n\r\n\t#tab_container_16686 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_16686 .wpsm_nav{\r\n\t\t\t}\r\n\r\n}\r\n\r\n\r\n\r\n@media (max-width: 768px) {\r\n\t#tab_container_16686 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_16686 .wpsm_nav{\r\n\t\t\t}\r\n}\r\n\r\n\r\n\t.wpsm_nav-tabs li:before{\r\n\t\tdisplay:none !important;\r\n\t}\r\n\r\n\t@media (max-width: 768px) {\r\n\t\t\t\t\r\n\t\t\t\t.wpsm_nav-tabs{\r\n\t\t\tmargin-left:0px !important;\r\n\t\t\tmargin-right:0px !important; \r\n\t\t\t\r\n\t\t}\r\n\t\t\t\t#tab_container_16686 .wpsm_nav-tabs > li{\r\n\t\t\tfloat:none !important;\r\n\t\t}\r\n\t\t\t\r\n\t}\t\t\t\t<\/style>\r\n\t\t\t\t<div id=\"tab_container_16686\" >\r\n\t \r\n\t\t\t\t\t<ul class=\"wpsm_nav wpsm_nav-tabs\" role=\"tablist\" id=\"myTab_16686\">\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  class=\"active\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_16686_1\" aria-controls=\"tabs_desc_16686_1\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Python<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\t\t\t\t <\/ul>\r\n\r\n\t\t\t\t\t  <!-- Tab panes -->\r\n\t\t\t\t\t  <div class=\"tab-content\" id=\"tab-content_16686\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane  in active \" id=\"tabs_desc_16686_1\">\r\n\t\t\t\t\t\t\t\t<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">def spiral_traversal_recursive(matrix, top, bottom, left, right, result):\r\n    if top &gt; bottom or left &gt; right:\r\n        return\r\n    for i in range(left, right + 1):\r\n        result.append(matrix[top][i])\r\n    top += 1\r\n\r\n    for i in range(top, bottom + 1):\r\n        result.append(matrix[i][right])\r\n    right -= 1\r\n\r\n    if top &lt;= bottom:\r\n        for i in range(right, left - 1, -1):\r\n            result.append(matrix[bottom][i])\r\n        bottom -= 1\r\n    if left &lt;= right:\r\n        for i in range(bottom, top - 1, -1):\r\n            result.append(matrix[i][left])\r\n        left += 1\r\n\r\n    spiral_traversal_recursive(matrix, top, bottom, left, right, result)\r\n\r\ndef spiral_traversal(matrix):\r\n    result = []\r\n    spiral_traversal_recursive(matrix, 0, len(matrix) - 1, 0, len(matrix[0]) - 1, result)\r\n    return result\r\n\r\n<\/pre>\r\n&nbsp;\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t <\/div>\r\n\t\t\t\t\t \r\n\t\t\t\t <\/div>\r\n <script>\r\n\t\tjQuery(function () {\r\n\t\t\tjQuery('#myTab_16686 a:first').tab('show')\r\n\t\t});\r\n\t\t\r\n\t\t\t\tjQuery(function(){\r\n\t\t\tvar b=\"fadeIn\";\r\n\t\t\tvar c;\r\n\t\t\tvar a;\r\n\t\t\td(jQuery(\"#myTab_16686 a\"),jQuery(\"#tab-content_16686\"));function d(e,f,g){\r\n\t\t\t\te.click(function(i){\r\n\t\t\t\t\ti.preventDefault();\r\n\t\t\t\t\tjQuery(this).tab(\"show\");\r\n\t\t\t\t\tvar h=jQuery(this).data(\"easein\");\r\n\t\t\t\t\tif(c){c.removeClass(a);}\r\n\t\t\t\t\tif(h){f.find(\"div.active\").addClass(\"animated \"+h);a=h;}\r\n\t\t\t\t\telse{if(g){f.find(\"div.active\").addClass(\"animated \"+g);a=g;}else{f.find(\"div.active\").addClass(\"animated \"+b);a=b;}}c=f.find(\"div.active\");\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\r\n\t\tfunction do_resize(){\r\n\r\n\t\t\tvar width=jQuery( '.tab-content .tab-pane iframe' ).width();\r\n\t\t\tvar height=jQuery( '.tab-content .tab-pane iframe' ).height();\r\n\r\n\t\t\tvar toggleSize = true;\r\n\t\t\tjQuery('iframe').animate({\r\n\t\t\t    width: toggleSize ? width : 640,\r\n\t\t\t    height: toggleSize ? height : 360\r\n\t\t\t  }, 250);\r\n\r\n\t\t\t  toggleSize = !toggleSize;\r\n\t\t}\r\n\r\n\r\n\t<\/script>\r\n\t\t\t\t\r\n\t\t\t\n<h2>Method 3: DFS Approach to solve spiral traversal of a matrix in Python<\/h2>\n<ol>\n<li>Create a DFS function that takes matrix, cell indices, and direction<\/li>\n<li>Checks are cell indices pointing to a valid cell (that is, not visited and in bounds)? if not, skip this cell<\/li>\n<li>Print cell value<\/li>\n<li>Mark matrix cell pointed by indicates as visited by changing it to a value not supported in the matrix<\/li>\n<li>Check are surrounding cells valid? if not stop the algorithm, else continue<\/li>\n<li>If the direction is given right then check if the cell to the right is valid. if so, DFS to the right cell given the steps above, else, change the direction to down and DFS downwards given the steps above<\/li>\n<li>Else, if the direction given is down then check, if the cell to the down is valid. if so, DFS to the cell below given the steps above, else, change the direction to left and DFS leftwards given the steps above<\/li>\n<li>Else, if the direction given is left then check, if the cell to the left is valid. if so, DFS to the left cell given the steps above, else, change the direction to up and DFS upwards given the steps above<\/li>\n<li>Otherwise, if the direction given is up then check if the cell to the up is valid. if so, DFS to the upper cell given the steps above, else, change the direction to right and DFS rightwards given the steps above<\/li>\n<\/ol>\n<h3>Python code for the DFS approach:<\/h3>\n\t\t\t\t\t\t<style>\r\n\t\t\t\t\r\n\t\t\t\t\t#tab_container_16687 {\r\n\toverflow:hidden;\r\n\tdisplay:block;\r\n\twidth:100%;\r\n\tborder:0px solid #ddd;\r\n\tmargin-bottom:30px;\r\n\t}\r\n\r\n#tab_container_16687 .tab-content{\r\n\tpadding:20px;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n\tmargin-top: 0px;\r\n\tbackground-color:#ffffff !important;\r\n\tcolor: #000000 !important;\r\n\tfont-size:16px !important;\r\n\tfont-family: Open Sans !important;\r\n\t\r\n\t\tborder: 1px solid #e6e6e6 !important;\r\n\t}\r\n#tab_container_16687 .wpsm_nav-tabs {\r\n    border-bottom: 0px solid #ddd;\r\n}\r\n#tab_container_16687 .wpsm_nav-tabs > li.active > a, #tab_container_16687 .wpsm_nav-tabs > li.active > a:hover, #tab_container_16687 .wpsm_nav-tabs > li.active > a:focus {\r\n\tcolor: #000000 !important;\r\n\tcursor: default;\r\n\tbackground-color: #ffffff !important;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n}\r\n\r\n#tab_container_16687 .wpsm_nav-tabs > li > a {\r\n    margin-right: 0px !important; \r\n    line-height: 1.42857143 !important;\r\n    border: 1px solid #d5d5d5 !important;\r\n    border-radius: 0px 0px 0 0 !important; \r\n\tbackground-color: #e8e8e8 !important;\r\n\tcolor: #000000 !important;\r\n\tpadding: 15px 18px 15px 18px !important;\r\n\ttext-decoration: none !important;\r\n\tfont-size: 14px !important;\r\n\ttext-align:center !important;\r\n\tfont-family: Open Sans !important;\r\n}\r\n#tab_container_16687 .wpsm_nav-tabs > li > a:focus {\r\noutline: 0px !important;\r\n}\r\n\r\n#tab_container_16687 .wpsm_nav-tabs > li > a:before {\r\n\tdisplay:none !important;\r\n}\r\n#tab_container_16687 .wpsm_nav-tabs > li > a:after {\r\n\tdisplay:none !important ;\r\n}\r\n#tab_container_16687 .wpsm_nav-tabs > li{\r\npadding:0px !important ;\r\nmargin:0px;\r\n}\r\n\r\n#tab_container_16687 .wpsm_nav-tabs > li > a:hover , #tab_container_16687 .wpsm_nav-tabs > li > a:focus {\r\n    color: #000000 !important;\r\n    background-color: #e8e8e8 !important;\r\n\tborder: 1px solid #d5d5d5 !important;\r\n\t\r\n}\r\n#tab_container_16687 .wpsm_nav-tabs > li > a .fa{\r\n\r\nmargin-right:5px !important;\r\n\r\nmargin-left:5px !important;\r\n\r\n\r\n}\r\n\r\n\t\t#tab_container_16687 .wpsm_nav-tabs a{\r\n\t\t\tbackground-image: none;\r\n\t\t\tbackground-position: 0 0;\r\n\t\t\tbackground-repeat: repeat-x;\r\n\t\t}\r\n\t\t\t\r\n\r\n\r\n#tab_container_16687 .wpsm_nav-tabs > li {\r\n    float: left;\r\n    margin-bottom: -1px !important;\r\n\tmargin-right:0px !important; \r\n}\r\n\r\n\r\n#tab_container_16687 .tab-content{\r\noverflow:hidden !important;\r\n}\r\n\r\n\r\n@media (min-width: 769px) {\r\n\r\n\t#tab_container_16687 .wpsm_nav-tabs > li{\r\n\t\tfloat:left !important ;\r\n\t\t\t\tmargin-right:-1px !important;\r\n\t\t\t\t\t}\r\n\t#tab_container_16687 .wpsm_nav-tabs{\r\n\t\tfloat:none !important;\r\n\t\tmargin:0px !important;\r\n\t}\r\n\r\n\t#tab_container_16687 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_16687 .wpsm_nav{\r\n\t\t\t}\r\n\r\n}\r\n\r\n\r\n\r\n@media (max-width: 768px) {\r\n\t#tab_container_16687 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_16687 .wpsm_nav{\r\n\t\t\t}\r\n}\r\n\r\n\r\n\t.wpsm_nav-tabs li:before{\r\n\t\tdisplay:none !important;\r\n\t}\r\n\r\n\t@media (max-width: 768px) {\r\n\t\t\t\t\r\n\t\t\t\t.wpsm_nav-tabs{\r\n\t\t\tmargin-left:0px !important;\r\n\t\t\tmargin-right:0px !important; \r\n\t\t\t\r\n\t\t}\r\n\t\t\t\t#tab_container_16687 .wpsm_nav-tabs > li{\r\n\t\t\tfloat:none !important;\r\n\t\t}\r\n\t\t\t\r\n\t}\t\t\t\t<\/style>\r\n\t\t\t\t<div id=\"tab_container_16687\" >\r\n\t \r\n\t\t\t\t\t<ul class=\"wpsm_nav wpsm_nav-tabs\" role=\"tablist\" id=\"myTab_16687\">\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  class=\"active\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_16687_1\" aria-controls=\"tabs_desc_16687_1\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Python<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\t\t\t\t <\/ul>\r\n\r\n\t\t\t\t\t  <!-- Tab panes -->\r\n\t\t\t\t\t  <div class=\"tab-content\" id=\"tab-content_16687\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane  in active \" id=\"tabs_desc_16687_1\">\r\n\t\t\t\t\t\t\t\t<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">R = 4\r\nC = 4\r\n\r\ndef isInBounds(i, j):\r\n    global R\r\n    global C\r\n    if (i &lt; 0 or i &gt;= R or j &lt; 0 or j &gt;= C):\r\n        return False\r\n    return True\r\n\r\ndef isBlocked(matrix, i, j):\r\n    if (not isInBounds(i, j)):\r\n        return True\r\n    if (matrix[i][j] == -1):\r\n        return True\r\n\r\n    return False\r\n\r\ndef spirallyDFSTraverse(matrix, i, j, Dir, res):\r\n    if (isBlocked(matrix, i, j)):\r\n        return\r\n\r\n    allBlocked = True\r\n    for k in range(-1, 2, 2):\r\n        allBlocked = allBlocked and isBlocked(\r\n            matrix, k + i, j) and isBlocked(matrix, i, j + k)\r\n\r\n    res.append(matrix[i][j])\r\n    matrix[i][j] = -1\r\n    if (allBlocked):\r\n        return\r\n\r\n    # dir: 0 - right, 1 - down, 2 - left, 3 - up\r\n    nxt_i = i\r\n    nxt_j = j\r\n    nxt_dir = Dir\r\n    if (Dir == 0):\r\n        if (not isBlocked(matrix, i, j + 1)):\r\n            nxt_j += 1\r\n        else:\r\n            nxt_dir = 1\r\n            nxt_i += 1\r\n\r\n    elif(Dir == 1):\r\n        if (not isBlocked(matrix, i + 1, j)):\r\n            nxt_i += 1\r\n        else:\r\n            nxt_dir = 2\r\n            nxt_j -= 1\r\n\r\n    elif(Dir == 2):\r\n        if (not isBlocked(matrix, i, j - 1)):\r\n            nxt_j -= 1\r\n        else:\r\n            nxt_dir = 3\r\n            nxt_i -= 1\r\n\r\n    elif(Dir == 3):\r\n        if (not isBlocked(matrix, i - 1, j)):\r\n            nxt_i -= 1\r\n        else:\r\n            nxt_dir = 0\r\n            nxt_j += 1\r\n\r\n    spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res)\r\n\r\ndef spirallyTraverse(matrix):\r\n    res = []\r\n    spirallyDFSTravserse(matrix, 0, 0, 0, res)\r\n    return res\r\n\r\nif __name__ == \"__main__\":\r\n    a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]\r\n\r\n    # Function Call\r\n    res = spirallyTraverse(a)\r\n    print(*res)\r\n<\/pre>\r\n&nbsp;\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t <\/div>\r\n\t\t\t\t\t \r\n\t\t\t\t <\/div>\r\n <script>\r\n\t\tjQuery(function () {\r\n\t\t\tjQuery('#myTab_16687 a:first').tab('show')\r\n\t\t});\r\n\t\t\r\n\t\t\t\tjQuery(function(){\r\n\t\t\tvar b=\"fadeIn\";\r\n\t\t\tvar c;\r\n\t\t\tvar a;\r\n\t\t\td(jQuery(\"#myTab_16687 a\"),jQuery(\"#tab-content_16687\"));function d(e,f,g){\r\n\t\t\t\te.click(function(i){\r\n\t\t\t\t\ti.preventDefault();\r\n\t\t\t\t\tjQuery(this).tab(\"show\");\r\n\t\t\t\t\tvar h=jQuery(this).data(\"easein\");\r\n\t\t\t\t\tif(c){c.removeClass(a);}\r\n\t\t\t\t\tif(h){f.find(\"div.active\").addClass(\"animated \"+h);a=h;}\r\n\t\t\t\t\telse{if(g){f.find(\"div.active\").addClass(\"animated \"+g);a=g;}else{f.find(\"div.active\").addClass(\"animated \"+b);a=b;}}c=f.find(\"div.active\");\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\r\n\t\tfunction do_resize(){\r\n\r\n\t\t\tvar width=jQuery( '.tab-content .tab-pane iframe' ).width();\r\n\t\t\tvar height=jQuery( '.tab-content .tab-pane iframe' ).height();\r\n\r\n\t\t\tvar toggleSize = true;\r\n\t\t\tjQuery('iframe').animate({\r\n\t\t\t    width: toggleSize ? width : 640,\r\n\t\t\t    height: toggleSize ? height : 360\r\n\t\t\t  }, 250);\r\n\r\n\t\t\t  toggleSize = !toggleSize;\r\n\t\t}\r\n\r\n\r\n\t<\/script>\r\n\t\t\t\t\r\n\t\t\t\n<h2>Method 4: Using deque to solve spiral traversal of a matrix in Python<\/h2>\n<ol>\n<li>Begin by setting the matrix&#8217;s boundaries to: &#8216;top&#8217; = 0, &#8216;bottom&#8217; = rows &#8211; 1, &#8216;left&#8217; = 0, &#8216;right&#8217; = columns &#8211; 1.<\/li>\n<li>Create an empty deque,&#8217;result,&#8217; in which to store the visited elements in spiral order.<\/li>\n<li>Repeat until &#8216;top = bottom&#8217; and &#8216;left = right&#8217;.<\/li>\n<li>From &#8216;left&#8217; to &#8216;right,&#8217; traverse the top row of the matrix, appending each element to the &#8216;result&#8217; deque.<\/li>\n<li>Increase the value of &#8216;top&#8217; by one to exclude the top row from future iterations.<\/li>\n<li>From &#8216;top&#8217; to &#8216;bottom,&#8217; traverse the right column of the matrix, appending each element to the &#8216;result&#8217; deque. <\/li>\n<li>Decrement <code>right<\/code> by 1 to exclude the right column from future iterations.<\/li>\n<li>Before proceeding, ensure that &#8216;top = bottom&#8217; and &#8216;left = right&#8217;.<\/li>\n<li>Traverse the matrix&#8217;s bottom row from &#8216;right&#8217; to &#8216;left,&#8217; appending each element to the &#8216;result&#8217; deque.<\/li>\n<li>Decrement <code>bottom<\/code> by 1 to exclude the bottom row from future iterations.<\/li>\n<li>Traverse the left column of the matrix from <code>bottom<\/code> to <code>top<\/code>, appending each element to the <code>result<\/code> deque.<\/li>\n<li>Increment <code>left<\/code> by 1 to exclude the left column from future iterations.<\/li>\n<li>Return the elements of the <code>result<\/code> deque as the spiral traversal of the matrix.<\/li>\n<\/ol>\n<h3>Python code for the deque approach:<\/h3>\n\t\t\t\t\t\t<style>\r\n\t\t\t\t\r\n\t\t\t\t\t#tab_container_16688 {\r\n\toverflow:hidden;\r\n\tdisplay:block;\r\n\twidth:100%;\r\n\tborder:0px solid #ddd;\r\n\tmargin-bottom:30px;\r\n\t}\r\n\r\n#tab_container_16688 .tab-content{\r\n\tpadding:20px;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n\tmargin-top: 0px;\r\n\tbackground-color:#ffffff !important;\r\n\tcolor: #000000 !important;\r\n\tfont-size:16px !important;\r\n\tfont-family: Open Sans !important;\r\n\t\r\n\t\tborder: 1px solid #e6e6e6 !important;\r\n\t}\r\n#tab_container_16688 .wpsm_nav-tabs {\r\n    border-bottom: 0px solid #ddd;\r\n}\r\n#tab_container_16688 .wpsm_nav-tabs > li.active > a, #tab_container_16688 .wpsm_nav-tabs > li.active > a:hover, #tab_container_16688 .wpsm_nav-tabs > li.active > a:focus {\r\n\tcolor: #000000 !important;\r\n\tcursor: default;\r\n\tbackground-color: #ffffff !important;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n}\r\n\r\n#tab_container_16688 .wpsm_nav-tabs > li > a {\r\n    margin-right: 0px !important; \r\n    line-height: 1.42857143 !important;\r\n    border: 1px solid #d5d5d5 !important;\r\n    border-radius: 0px 0px 0 0 !important; \r\n\tbackground-color: #e8e8e8 !important;\r\n\tcolor: #000000 !important;\r\n\tpadding: 15px 18px 15px 18px !important;\r\n\ttext-decoration: none !important;\r\n\tfont-size: 14px !important;\r\n\ttext-align:center !important;\r\n\tfont-family: Open Sans !important;\r\n}\r\n#tab_container_16688 .wpsm_nav-tabs > li > a:focus {\r\noutline: 0px !important;\r\n}\r\n\r\n#tab_container_16688 .wpsm_nav-tabs > li > a:before {\r\n\tdisplay:none !important;\r\n}\r\n#tab_container_16688 .wpsm_nav-tabs > li > a:after {\r\n\tdisplay:none !important ;\r\n}\r\n#tab_container_16688 .wpsm_nav-tabs > li{\r\npadding:0px !important ;\r\nmargin:0px;\r\n}\r\n\r\n#tab_container_16688 .wpsm_nav-tabs > li > a:hover , #tab_container_16688 .wpsm_nav-tabs > li > a:focus {\r\n    color: #000000 !important;\r\n    background-color: #e8e8e8 !important;\r\n\tborder: 1px solid #d5d5d5 !important;\r\n\t\r\n}\r\n#tab_container_16688 .wpsm_nav-tabs > li > a .fa{\r\n\r\nmargin-right:5px !important;\r\n\r\nmargin-left:5px !important;\r\n\r\n\r\n}\r\n\r\n\t\t#tab_container_16688 .wpsm_nav-tabs a{\r\n\t\t\tbackground-image: none;\r\n\t\t\tbackground-position: 0 0;\r\n\t\t\tbackground-repeat: repeat-x;\r\n\t\t}\r\n\t\t\t\r\n\r\n\r\n#tab_container_16688 .wpsm_nav-tabs > li {\r\n    float: left;\r\n    margin-bottom: -1px !important;\r\n\tmargin-right:0px !important; \r\n}\r\n\r\n\r\n#tab_container_16688 .tab-content{\r\noverflow:hidden !important;\r\n}\r\n\r\n\r\n@media (min-width: 769px) {\r\n\r\n\t#tab_container_16688 .wpsm_nav-tabs > li{\r\n\t\tfloat:left !important ;\r\n\t\t\t\tmargin-right:-1px !important;\r\n\t\t\t\t\t}\r\n\t#tab_container_16688 .wpsm_nav-tabs{\r\n\t\tfloat:none !important;\r\n\t\tmargin:0px !important;\r\n\t}\r\n\r\n\t#tab_container_16688 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_16688 .wpsm_nav{\r\n\t\t\t}\r\n\r\n}\r\n\r\n\r\n\r\n@media (max-width: 768px) {\r\n\t#tab_container_16688 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_16688 .wpsm_nav{\r\n\t\t\t}\r\n}\r\n\r\n\r\n\t.wpsm_nav-tabs li:before{\r\n\t\tdisplay:none !important;\r\n\t}\r\n\r\n\t@media (max-width: 768px) {\r\n\t\t\t\t\r\n\t\t\t\t.wpsm_nav-tabs{\r\n\t\t\tmargin-left:0px !important;\r\n\t\t\tmargin-right:0px !important; \r\n\t\t\t\r\n\t\t}\r\n\t\t\t\t#tab_container_16688 .wpsm_nav-tabs > li{\r\n\t\t\tfloat:none !important;\r\n\t\t}\r\n\t\t\t\r\n\t}\t\t\t\t<\/style>\r\n\t\t\t\t<div id=\"tab_container_16688\" >\r\n\t \r\n\t\t\t\t\t<ul class=\"wpsm_nav wpsm_nav-tabs\" role=\"tablist\" id=\"myTab_16688\">\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  class=\"active\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_16688_1\" aria-controls=\"tabs_desc_16688_1\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-laptop\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Python<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\t\t\t\t <\/ul>\r\n\r\n\t\t\t\t\t  <!-- Tab panes -->\r\n\t\t\t\t\t  <div class=\"tab-content\" id=\"tab-content_16688\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane  in active \" id=\"tabs_desc_16688_1\">\r\n\t\t\t\t\t\t\t\t<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">from collections import deque\r\n\r\ndef spiral_traversal(matrix):\r\n    if not matrix:\r\n        return []\r\n\r\n    rows, cols = len(matrix), len(matrix[0])\r\n    top, bottom, left, right = 0, rows - 1, 0, cols - 1\r\n    result = deque()\r\n\r\n    while top &lt;= bottom and left &lt;= right:\r\n        for i in range(left, right + 1):\r\n            result.append(matrix[top][i])\r\n        top += 1\r\n\r\n        for i in range(top, bottom + 1):\r\n            result.append(matrix[i][right])\r\n        right -= 1\r\n\r\n        if top &lt;= bottom:\r\n            for i in range(right, left - 1, -1):\r\n                result.append(matrix[bottom][i])\r\n            bottom -= 1\r\n\r\n        if left &lt;= right:\r\n            for i in range(bottom, top - 1, -1):\r\n                result.append(matrix[i][left])\r\n            left += 1\r\n\r\n    return list(result)\r\n<\/pre>\r\n&nbsp;\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t <\/div>\r\n\t\t\t\t\t \r\n\t\t\t\t <\/div>\r\n <script>\r\n\t\tjQuery(function () {\r\n\t\t\tjQuery('#myTab_16688 a:first').tab('show')\r\n\t\t});\r\n\t\t\r\n\t\t\t\tjQuery(function(){\r\n\t\t\tvar b=\"fadeIn\";\r\n\t\t\tvar c;\r\n\t\t\tvar a;\r\n\t\t\td(jQuery(\"#myTab_16688 a\"),jQuery(\"#tab-content_16688\"));function d(e,f,g){\r\n\t\t\t\te.click(function(i){\r\n\t\t\t\t\ti.preventDefault();\r\n\t\t\t\t\tjQuery(this).tab(\"show\");\r\n\t\t\t\t\tvar h=jQuery(this).data(\"easein\");\r\n\t\t\t\t\tif(c){c.removeClass(a);}\r\n\t\t\t\t\tif(h){f.find(\"div.active\").addClass(\"animated \"+h);a=h;}\r\n\t\t\t\t\telse{if(g){f.find(\"div.active\").addClass(\"animated \"+g);a=g;}else{f.find(\"div.active\").addClass(\"animated \"+b);a=b;}}c=f.find(\"div.active\");\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\r\n\t\tfunction do_resize(){\r\n\r\n\t\t\tvar width=jQuery( '.tab-content .tab-pane iframe' ).width();\r\n\t\t\tvar height=jQuery( '.tab-content .tab-pane iframe' ).height();\r\n\r\n\t\t\tvar toggleSize = true;\r\n\t\t\tjQuery('iframe').animate({\r\n\t\t\t    width: toggleSize ? width : 640,\r\n\t\t\t    height: toggleSize ? height : 360\r\n\t\t\t  }, 250);\r\n\r\n\t\t\t  toggleSize = !toggleSize;\r\n\t\t}\r\n\r\n\r\n\t<\/script>\r\n\t\t\t\t\r\n\t\t\t\n<p><strong>Conclusion<\/strong><br \/>\nA matrix spiral traversal is a useful technique in a variety of programming scenarios. In this article, we discussed two approaches: iterative and recursive. The iterative approach iterates through the matrix using a while loop, whereas the recursive approach traverses the elements using a helper function. You can efficiently perform a spiral traversal of a matrix and retrieve the elements in the desired order by implementing the provided algorithms in Python.<\/p>\n<h2>Frequently Asked Questions (FAQs)<\/h2>\n<p><strong>Q1 What are the advantages of using a deque for spiral traversal?<\/strong><br \/>\nWhen traversing the matrix in a spiral pattern, using a deque allows for efficient insertion and deletion at both ends, which is advantageous. It allows you to append elements from all sides without having to manage indexes manually.<\/p>\n<p><strong>Q2. Could you explain the distinction between iterative and recursive approaches?<\/strong><br \/>\nThe iterative approach traverses the matrix in a spiral pattern using loops and boundary variables, whereas the recursive approach uses a recursive function with updated boundaries to achieve the same result.  Personal preference and specific programming requirements dictate which approach is used.<\/p>\n<p><strong>Q3. What if the matrix is empty or has incorrect dimensions?<\/strong><br \/>\nBoth the iterative and recursive approaches will return an empty result if the matrix is empty. For invalid dimensions, the behavior may vary depending on the implementation. For proper traversal, it is generally assumed that the matrix has valid dimensions.<\/p>\n<p><strong>Q4. How do I incorporate the spiral traversal algorithm into my own code?<\/strong><br \/>\nTo use the spiral traversal algorithm in your code, define the appropriate function (iterative or recursive) and pass your matrix as an argument. The function will return a list or deque containing the matrix elements in spiral order, which you can then process as necessary.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The traversal of a matrix is a common operation in many programming tasks. The spiral traversal is a specific traversal pattern in which the elements of the matrix are visited in a spiral-like order, beginning at the top-left corner and moving clockwise until all elements are visited. In this article, we will look at various [&hellip;]<\/p>\n","protected":false},"author":52,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[154],"tags":[],"class_list":["post-16684","post","type-post","status-publish","format-standard","hentry","category-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.8 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Spiral Traversal Of A Matrix In Python<\/title>\n<meta name=\"description\" content=\"Spiral Traversal Of A Matrix In Python is a specific traversal pattern in which the elements of the matrix are visited in a spiral-like order.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Spiral Traversal Of A Matrix In Python\" \/>\n<meta property=\"og:description\" content=\"Spiral Traversal Of A Matrix In Python is a specific traversal pattern in which the elements of the matrix are visited in a spiral-like order.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/\" \/>\n<meta property=\"og:site_name\" content=\"PrepBytes Blog\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/prepbytes0211\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-06-05T10:12:20+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-06-05T10:20:30+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1685958822756-Spiral%20traversal%20of%20a%20matrix%20in%20Python.jpg\" \/>\n<meta name=\"author\" content=\"Prepbytes\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Prepbytes\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/\"},\"author\":{\"name\":\"Prepbytes\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/3f7dc4ae851791d5947a7f99df363d5e\"},\"headline\":\"Spiral Traversal Of A Matrix In Python\",\"datePublished\":\"2023-06-05T10:12:20+00:00\",\"dateModified\":\"2023-06-05T10:20:30+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/\"},\"wordCount\":1189,\"commentCount\":0,\"publisher\":{\"@id\":\"http:\/\/43.205.93.38\/#organization\"},\"image\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1685958822756-Spiral%20traversal%20of%20a%20matrix%20in%20Python.jpg\",\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/\",\"url\":\"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/\",\"name\":\"Spiral Traversal Of A Matrix In Python\",\"isPartOf\":{\"@id\":\"http:\/\/43.205.93.38\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1685958822756-Spiral%20traversal%20of%20a%20matrix%20in%20Python.jpg\",\"datePublished\":\"2023-06-05T10:12:20+00:00\",\"dateModified\":\"2023-06-05T10:20:30+00:00\",\"description\":\"Spiral Traversal Of A Matrix In Python is a specific traversal pattern in which the elements of the matrix are visited in a spiral-like order.\",\"breadcrumb\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/#primaryimage\",\"url\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1685958822756-Spiral%20traversal%20of%20a%20matrix%20in%20Python.jpg\",\"contentUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1685958822756-Spiral%20traversal%20of%20a%20matrix%20in%20Python.jpg\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"http:\/\/43.205.93.38\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python\",\"item\":\"https:\/\/prepbytes.com\/blog\/category\/python\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Spiral Traversal Of A Matrix In Python\"}]},{\"@type\":\"WebSite\",\"@id\":\"http:\/\/43.205.93.38\/#website\",\"url\":\"http:\/\/43.205.93.38\/\",\"name\":\"PrepBytes Blog\",\"description\":\"ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING\",\"publisher\":{\"@id\":\"http:\/\/43.205.93.38\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"http:\/\/43.205.93.38\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"http:\/\/43.205.93.38\/#organization\",\"name\":\"Prepbytes\",\"url\":\"http:\/\/43.205.93.38\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp\",\"contentUrl\":\"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp\",\"width\":160,\"height\":160,\"caption\":\"Prepbytes\"},\"image\":{\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/prepbytes0211\/\",\"https:\/\/www.instagram.com\/prepbytes\/\",\"https:\/\/www.linkedin.com\/company\/prepbytes\/\",\"https:\/\/www.youtube.com\/channel\/UC0xGnHDrjUM1pDEK2Ka5imA\"]},{\"@type\":\"Person\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/3f7dc4ae851791d5947a7f99df363d5e\",\"name\":\"Prepbytes\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/232042cd1a1ea0e982c96d2a2ec93fb70a8e864e00784491231e7bfe5a9e06b5?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/232042cd1a1ea0e982c96d2a2ec93fb70a8e864e00784491231e7bfe5a9e06b5?s=96&d=mm&r=g\",\"caption\":\"Prepbytes\"},\"url\":\"https:\/\/prepbytes.com\/blog\/author\/gourav-jaincollegedekho-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Spiral Traversal Of A Matrix In Python","description":"Spiral Traversal Of A Matrix In Python is a specific traversal pattern in which the elements of the matrix are visited in a spiral-like order.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/","og_locale":"en_US","og_type":"article","og_title":"Spiral Traversal Of A Matrix In Python","og_description":"Spiral Traversal Of A Matrix In Python is a specific traversal pattern in which the elements of the matrix are visited in a spiral-like order.","og_url":"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/","og_site_name":"PrepBytes Blog","article_publisher":"https:\/\/www.facebook.com\/prepbytes0211\/","article_published_time":"2023-06-05T10:12:20+00:00","article_modified_time":"2023-06-05T10:20:30+00:00","og_image":[{"url":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1685958822756-Spiral%20traversal%20of%20a%20matrix%20in%20Python.jpg","type":"","width":"","height":""}],"author":"Prepbytes","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Prepbytes","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/#article","isPartOf":{"@id":"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/"},"author":{"name":"Prepbytes","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/3f7dc4ae851791d5947a7f99df363d5e"},"headline":"Spiral Traversal Of A Matrix In Python","datePublished":"2023-06-05T10:12:20+00:00","dateModified":"2023-06-05T10:20:30+00:00","mainEntityOfPage":{"@id":"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/"},"wordCount":1189,"commentCount":0,"publisher":{"@id":"http:\/\/43.205.93.38\/#organization"},"image":{"@id":"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1685958822756-Spiral%20traversal%20of%20a%20matrix%20in%20Python.jpg","articleSection":["Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/","url":"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/","name":"Spiral Traversal Of A Matrix In Python","isPartOf":{"@id":"http:\/\/43.205.93.38\/#website"},"primaryImageOfPage":{"@id":"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/#primaryimage"},"image":{"@id":"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1685958822756-Spiral%20traversal%20of%20a%20matrix%20in%20Python.jpg","datePublished":"2023-06-05T10:12:20+00:00","dateModified":"2023-06-05T10:20:30+00:00","description":"Spiral Traversal Of A Matrix In Python is a specific traversal pattern in which the elements of the matrix are visited in a spiral-like order.","breadcrumb":{"@id":"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/#primaryimage","url":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1685958822756-Spiral%20traversal%20of%20a%20matrix%20in%20Python.jpg","contentUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1685958822756-Spiral%20traversal%20of%20a%20matrix%20in%20Python.jpg"},{"@type":"BreadcrumbList","@id":"https:\/\/prepbytes.com\/blog\/spiral-traversal-of-a-matrix-in-python\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/43.205.93.38\/"},{"@type":"ListItem","position":2,"name":"Python","item":"https:\/\/prepbytes.com\/blog\/category\/python\/"},{"@type":"ListItem","position":3,"name":"Spiral Traversal Of A Matrix In Python"}]},{"@type":"WebSite","@id":"http:\/\/43.205.93.38\/#website","url":"http:\/\/43.205.93.38\/","name":"PrepBytes Blog","description":"ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING","publisher":{"@id":"http:\/\/43.205.93.38\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"http:\/\/43.205.93.38\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"http:\/\/43.205.93.38\/#organization","name":"Prepbytes","url":"http:\/\/43.205.93.38\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/","url":"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp","contentUrl":"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp","width":160,"height":160,"caption":"Prepbytes"},"image":{"@id":"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/prepbytes0211\/","https:\/\/www.instagram.com\/prepbytes\/","https:\/\/www.linkedin.com\/company\/prepbytes\/","https:\/\/www.youtube.com\/channel\/UC0xGnHDrjUM1pDEK2Ka5imA"]},{"@type":"Person","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/3f7dc4ae851791d5947a7f99df363d5e","name":"Prepbytes","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/232042cd1a1ea0e982c96d2a2ec93fb70a8e864e00784491231e7bfe5a9e06b5?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/232042cd1a1ea0e982c96d2a2ec93fb70a8e864e00784491231e7bfe5a9e06b5?s=96&d=mm&r=g","caption":"Prepbytes"},"url":"https:\/\/prepbytes.com\/blog\/author\/gourav-jaincollegedekho-com\/"}]}},"_links":{"self":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/16684","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/users\/52"}],"replies":[{"embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/comments?post=16684"}],"version-history":[{"count":2,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/16684\/revisions"}],"predecessor-version":[{"id":16690,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/16684\/revisions\/16690"}],"wp:attachment":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/media?parent=16684"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/categories?post=16684"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/tags?post=16684"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}