JavaScript Program to Print Given Matrix in Spiral Form
Last Updated :
23 Jul, 2025
Write a JavaScript program to print a given 2D matrix in spiral form.
You are given a two-dimensional matrix of integers. Write a program to traverse the matrix starting from the top-left corner which moves right, bottom, left, and up in a spiral pattern until all the elements are visited. Let us understand it with the examples and figures given below:
Examples:
Example 1:
Input: matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Output: [1 2 3 6 9 8 7 4 5]
Spiral Matrix Example-1
Example 2:
Input: matrix = [[1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7]]
Output: [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
Spiral Matrix Example-2To print a given matrix in a spiral form we initialize boundaries to track the matrix's edges. Then iterate through the matrix, printing elements in a clockwise spiral pattern: top row, right column, bottom row, left column. Adjust boundaries after each step and continue until all elements are printed.
- Initialize four variables to represent the boundaries of the matrix:
- top: The topmost row.
- bottom: The bottommost row.
- left: The leftmost column.
- right: The rightmost column.
- Iterate over all the elements of the matrix:
- Print all elements of the top row from left to right and increment the top pointer to move to the next row.
- Now, print all elements of the right column from top to bottom and decrement the right pointer to the previous column.
- Check that, if the top pointer is still less than or equal to the bottom boundary.
- If yes, then print all elements of the bottom row from right to left and decrement the bottom to its previous row.
- Again check if the left pointer is still less than or equal to the right boundary.If yes, then print all elements of the left column from bottom to top and increment the left to its next column.
- Repeat the above steps until all elements are printed.
Example: Below is the implementation of the above approach:
JavaScript
// JavaScript code for the above approach
function printSpiral(matrix) {
let result = [];
let top = 0;
let bottom = matrix.length - 1;
let left = 0;
let right = matrix[0].length - 1;
// Loop while the elements
// are within the boundaries.
while (top <= bottom
&& left <= right) {
// Print top row
for (let i = left;
i <= right; i++) {
result.push(matrix[top][i]);
}
// Move the top boundary down.
top++;
// Print right column
for (let i = top;
i <= bottom; i++) {
result.push(matrix[i][right]);
}
// Move the right boundary to the left.
right--;
// Check if there are more rows
if (top <= bottom) {
// Print bottom row
for (let i = right;
i >= left; i--) {
result.push(matrix[bottom][i]);
}
// Move the bottom boundary up.
bottom--;
}
// Check if there are more columns
if (left <= right) {
// Print left column
for (let i = bottom;
i >= top; i--) {
result.push(matrix[i][left]);
}
// Move the left boundary to the right.
left++;
}
}
// Print the result
console.log(result.join(' '));
}
// Example
const matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
];
printSpiral(matrix);
Output1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Time Complexity: O(m * n): The time complexity of this code is O(m * n), where 'm' is the number of rows in the matrix, and 'n' is the number of columns in the matrix. This is because we visit each element in the matrix exactly once in a linear fashion.
Space Complexity: O(m * n): The space complexity is O(m * n) as well. The primary space consumption comes from the result array, which stores all the elements of the matrix in spiral order. The size of this array is directly proportional to the number of elements in the matrix, which is 'm * n'.
Method 2: Using Simulation Approach
- We are given a matrix of 'N' rows and 'M' columns.
- Use a visited array where vis[n][m] indicates whether the cell at row 'n' and column 'm' has been visited.
- Our current position is denoted by (n, m), and we're facing a certain direction d. We have to visit all the N x M cells in the matrix.
- As we traverse through the matrix, we continuously calculate a cell's next position, denoted as (nrow, ncol).
- If the cell's position is within the bounds of the matrix and has not been visited (!vis[nrow][nrow]), it becomes our next position.
- If the cell's position is out of bounds or has already been visited, we change our next position to the one by performing a clockwise turn.
Example: Below is the implementation of the above approach:
JavaScript
// JavaScript code for the above approach
function spiralOrder(matrix) {
let result = [];
if (matrix.length === 0) {
return result;
}
let N = matrix.length;
let M = matrix[0].length;
// Create a visited matrix
let vis = new Array(N);
for (let n = 0; n < N; n++) {
vis[n] = new Array(M).fill(false);
}
let dx = [0, 1, 0, -1];
let dy = [1, 0, -1, 0];
let n = 0, m = 0, d = 0;
// Traverse through the matrix
for (let i = 0; i < N * M; i++) {
result.push(matrix[n][m]);
vis[n][m] = true;
// Calculate the next
// cell's position
let nrow = n + dx[d];
let ncol = m + dy[d];
// Check the valid positions
// of the cell
if (nrow >= 0 && nrow < N
&& ncol >= 0 && ncol < M
&& !vis[nrow][ncol]
) {
n = nrow;
m = ncol;
} else {
// Perform a clockwise
// turn to change direction
d = (d + 1) % 4;
n += dx[d];
m += dy[d];
}
}
return result.join(' ');
}
// Example
const matrix = [
[1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7],
];
let spiralResult = spiralOrder(matrix);
console.log(spiralResult);
Output1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Time Complexity: O(N * M).
Space Complexity: O(N * M).
Method 3: Using Recursion in JavaScript
- Create a recursive function that takes a matrix and four variables: k (starting row index), m (ending row index), l (starting column index), and n (ending column index) as the parameters.
- As a base case, the starting index should be less than or equal to the ending index for both rows and columns.
- Now print the boundary elements in a clockwise manner as given in below steps:
- First, print the top row elements. This means print the elements of the k-th row from column index l to n. Then increment the value of k.
- Next, print the right column elements. Print the last column from row index k to m. Then decrease the value of n.
- If k is greater than m, print the bottom row elements. That is, the elements of the (m-1)th row from column n-1 to l and decrement the value of m.
- If l is less than n, print the left column elements of the l-th column from the (m-1)th row to k and increment the value of l.
- Recursively call the function with the updated values of starting and ending indices for rows and columns.
Example: Below is the implementation of the above approach:
JavaScript
// JavaScript code for the above approach
function printSpiralRecursive(matrix, k, m, l, n) {
// Base case
if (k > m || l > n) {
return '';
}
let result = '';
// Print the top row from left to right
for (let i = l; i <= n; i++) {
result += matrix[k][i] + ' ';
}
// Increment the row index from start
k++;
// Print the right column from top to bottom
for (let i = k; i <= m; i++) {
result += matrix[i][n] + ' ';
}
// Decrement the column index from end
n--;
// Check if there is a bottom row to print
if (k <= m) {
for (let i = n; i >= l; i--) {
result += matrix[m][i] + ' ';
}
// Decrement the row index from end
m--;
}
// Check if there is a left column to print
if (l <= n) {
for (let i = m; i >= k; i--) {
result += matrix[i][l] + ' ';
}
// Increment the column index from start
l++;
}
// Recursive Call
return result +
printSpiralRecursive(matrix, k, m, l, n);
}
// Function to print the matrix in spiral form
function printSpiral(matrix) {
const rows =
matrix.length;
const columns =
matrix[0].length;
const spiralResult =
printSpiralRecursive(matrix, 0, rows - 1,
0, columns - 1);
console.log(spiralResult);
}
// Example
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
printSpiral(matrix);
Time Complexity: O(N*M). To traverse the entire matrix O(N*M) time is required.
Space Complexity: O(1). As we do not use any external data structure here, there is constant space. But obviously the algorithm will consume a recursive stack space of O(n).
Method 4: Using Depth First Search (DFS)
- Create an array of N*M for marking the visited cells so far. Initially, all the cells will be unvisited.
- Create arrays called dx (for rows) and dy (for columns) to represent the four possible adjacent directions for each cell.
- Now, in the recursive DFS function, the current row, column and the direction will be the parameters.
- As a base case, check if the current cell is within the bounds of the given matrix and if the cell has not been visited earlier.
- If not, then mark it as visited and print its value.
- Calculate the value of the next row and column by adding the respective values from dx and dy arrays. Make a recursive call in the new indices of those directions.
- When one traversal gets complete, change the direction to the next clockwise direction to print the matrix spirally.
- Start the DFS from the top-left corner of the given matrix which will be the first cell.
Example: Below is the implementation of the above approach:
JavaScript
// JavaScript code for the above approach
function spiralDFS(matrix) {
const N = matrix.length;
const M = matrix[0].length;
// Initialize a visited array
let vis = new Array(N);
for (let n = 0; n < N; n++) {
vis[n] = new Array(M).fill(false);
}
// Row and column directions for
// right, down, left, and up
const dx = [0, 1, 0, -1];
const dy = [1, 0, -1, 0];
let i = 0;
let row = 0;
let col = 0;
const result = [];
// DFS function
function dfs(row, col) {
// Base case: Check if the current
// cell is within bounds and unvisited
if (row < 0 || row >= N ||
col < 0 || col >= M ||
vis[row][col]) {
return;
}
// Mark the cell as visited
// and add it to the result
result.push(matrix[row][col]);
vis[row][col] = true;
// Calculate the next row and column
const nrow = row + dx[i];
const ncol = col + dy[i];
// Recursively call DFS with the new indices
dfs(nrow, ncol);
// If DFS completes in the current
// direction, change direction clockwise
if (nrow < 0 || nrow >= N ||
ncol < 0 || ncol >= M ||
vis[nrow][ncol]) {
i = (i + 1) % 4;
const nrow = row + dx[i];
const ncol = col + dy[i];
dfs(nrow, ncol);
}
}
// Start DFS from the top-left
// corner of the matrix
dfs(row, col);
console.log(result.join(' '));
}
// Example
const matrix = [
[1, 2, 3],
[6, 5, 7],
[4, 8, 11],
[12, 0, 16]
];
spiralDFS(matrix);
Output1 2 3 7 11 16 0 12 4 6 5 8
Time Complexity: O(N*M) To traverse the entire matrix O(m*n) time is required.
Space Complexity: O(N*M) We use an external data structure here, which is a 2D visited matrix. Also, the algorithm will consume a recursive stack space.
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.Client Side: On the client side, JavaScript works
11 min read
JavaScript Basics
Introduction to JavaScriptJavaScript is a versatile, dynamically typed programming language that brings life to web pages by making them interactive. It is used for building interactive web applications, supports both client-side and server-side development, and integrates seamlessly with HTML, CSS, and a rich standard libra
4 min read
JavaScript VersionsJavaScript is a popular programming language used by developers all over the world. Itâs a lightweight and easy-to-learn language that can run on both the client-side (in your browser) and the server-side (on the server). JavaScript was created in 1995 by Brendan Eich.In 1997, JavaScript became a st
2 min read
How to Add JavaScript in HTML Document?To add JavaScript in HTML document, several methods can be used. These methods include embedding JavaScript directly within the HTML file or linking an external JavaScript file.Inline JavaScriptYou can write JavaScript code directly inside the HTML element using the onclick, onmouseover, or other ev
3 min read
JavaScript SyntaxJavaScript syntax refers to the rules and conventions dictating how code is structured and arranged within the JavaScript programming language. This includes statements, expressions, variables, functions, operators, and control flow constructs.Syntaxconsole.log("Basic Print method in JavaScript");Ja
6 min read
JavaScript OutputJavaScript provides different methods to display output, such as console.log(), alert(), document.write(), and manipulating HTML elements directly. Each method has its specific use cases, whether for debugging, user notifications, or dynamically updating web content. Here we will explore various Jav
4 min read
JavaScript CommentsComments help explain code (they are not executed and hence do not have any logic implementation). We can also use them to temporarily disable parts of your code.1. Single Line CommentsA single-line comment in JavaScript is denoted by two forward slashes (//), JavaScript// A single line comment cons
2 min read
JS Variables & Datatypes
Variables and Datatypes in JavaScriptVariables and data types are foundational concepts in programming, serving as the building blocks for storing and manipulating information within a program. In JavaScript, getting a good grasp of these concepts is important for writing code that works well and is easy to understand.Data TypesVariabl
6 min read
Global and Local variables in JavaScriptIn JavaScript, understanding the difference between global and local variables is important for writing clean, maintainable, and error-free code. Variables can be declared with different scopes, affecting where and how they can be accessed. Global VariablesGlobal variables in JavaScript are those de
4 min read
JavaScript LetThe let keyword is a modern way to declare variables in JavaScript and was introduced in ECMAScript 6 (ES6). Unlike var, let provides block-level scoping. This behaviour helps developers avoid unintended issues caused by variable hoisting and scope leakage that are common with var.Syntaxlet variable
6 min read
JavaScript constThe const keyword in JavaScript is a modern way to declare variables, introduced in (ES6). It is used to declare variables whose values need to remain constant throughout the lifetime of the application.const is block-scoped, similar to let, and is useful for ensuring immutability in your code. Unli
5 min read
JavaScript Var StatementThe var keyword is used to declare variables in JavaScript. It has been part of the language since its inception. When a variable is declared using var, it is function-scoped or globally-scoped, depending on where it is declared.Syntaxvar variable = value;It declares a variable using var, assigns it
7 min read
JS Operators
JavaScript OperatorsJavaScript operators are symbols or keywords used to perform operations on values and variables. They are the building blocks of JavaScript expressions and can manipulate data in various ways.There are various operators supported by JavaScript:1. JavaScript Arithmetic OperatorsArithmetic Operators p
5 min read
Operator precedence in JavaScriptOperator precedence refers to the priority given to operators while parsing a statement that has more than one operator performing operations in it. Operators with higher priorities are resolved first. But as one goes down the list, the priority decreases and hence their resolution. ( * ) and ( / )
2 min read
JavaScript Arithmetic OperatorsJavaScript Arithmetic Operators are the operator that operate upon the numerical values and return a numerical value. Addition (+) OperatorThe addition operator takes two numerical operands and gives their numerical sum. It also concatenates two strings or numbers.JavaScript// Number + Number =>
5 min read
JavaScript Assignment OperatorsAssignment operators are used to assign values to variables in JavaScript.JavaScript// Lets take some variables x = 10 y = 20 x = y ; console.log(x); console.log(y); Output20 20 More Assignment OperatorsThere are so many assignment operators as shown in the table with the description.OPERATOR NAMESH
5 min read
JavaScript Comparison OperatorsJavaScript comparison operators are essential tools for checking conditions and making decisions in your code. 1. Equality Operator (==) The Equality operator is used to compare the equality of two operands. JavaScript// Illustration of (==) operator let x = 5; let y = '5'; // Checking of operands c
5 min read
JavaScript Logical OperatorsLogical operators in JavaScript are used to perform logical operations on values and return either true or false. These operators are commonly used in decision-making statements like if or while loops to control the flow of execution based on conditions.In JavaScript, there are basically three types
5 min read
JavaScript Bitwise OperatorsIn JavaScript, a number is stored as a 64-bit floating-point number but bitwise operations are performed on a 32-bit binary number. To perform a bit-operation, JavaScript converts the number into a 32-bit binary number (signed) and performs the operation and converts back the result to a 64-bit numb
5 min read
JavaScript Ternary OperatorThe Ternary Operator in JavaScript is a conditional operator that evaluates a condition and returns one of two values based on whether the condition is true or false. It simplifies decision-making in code, making it more concise and readable. Syntaxcondition ? trueExpression : falseExpressionConditi
4 min read
JavaScript Comma OperatorJavaScript Comma Operator mainly evaluates its operands from left to right sequentially and returns the value of the rightmost operand. JavaScriptlet x = (1, 2, 3); console.log(x); Output3 Here is another example to show that all expressions are actually executed.JavaScriptlet a = 1, b = 2, c = 3; l
2 min read
JavaScript Unary OperatorsJavaScript Unary Operators work on a single operand and perform various operations, like incrementing/decrementing, evaluating data type, negation of a value, etc.Unary Plus (+) OperatorThe unary plus (+) converts an operand into a number, if possible. It is commonly used to ensure numerical operati
4 min read
JavaScript in and instanceof operatorsJavaScript Relational Operators are used to compare their operands and determine the relationship between them. They return a Boolean value (true or false) based on the comparison result.JavaScript in OperatorThe in-operator in JavaScript checks if a specified property exists in an object or if an e
3 min read
JavaScript String OperatorsJavaScript String Operators are used to manipulate and perform operations on strings. There are two operators which are used to modify strings in JavaScript. These operators help us to join one string to another string.1. Concatenate OperatorConcatenate Operator in JavaScript combines strings using
3 min read
JS Statements
JS Loops
JavaScript LoopsLoops in JavaScript are used to reduce repetitive tasks by repeatedly executing a block of code as long as a specified condition is true. This makes code more concise and efficient.Suppose we want to print 'Hello World' five times. Instead of manually writing the print statement repeatedly, we can u
3 min read
JavaScript For LoopJavaScript for loop is a control flow statement that allows code to be executed repeatedly based on a condition. It consists of three parts: initialization, condition, and increment/decrement. Syntaxfor (statement 1 ; statement 2 ; statement 3){ code here...}Statement 1: It is the initialization of
4 min read
JavaScript While LoopThe while loop executes a block of code as long as a specified condition is true. In JavaScript, this loop evaluates the condition before each iteration and continues running as long as the condition remains true.Syntaxwhile (condition) { Code block to be executed}Here's an example that prints from
3 min read
JavaScript For In LoopThe JavaScript for...in loop iterates over the properties of an object. It allows you to access each key or property name of an object.JavaScriptconst car = { make: "Toyota", model: "Corolla", year: 2020 }; for (let key in car) { console.log(`${key}: ${car[key]}`); }Outputmake: Toyota model: Corolla
3 min read
JavaScript for...of LoopThe JavaScript for...of loop is a modern, iteration statement introduced in ECMAScript 2015 (ES6). Works for iterable objects such as arrays, strings, maps, sets, and more. It is better choice for traversing items of iterables compared to traditional for and for in loops, especially when we have bre
3 min read
JavaScript do...while LoopA do...while loop in JavaScript is a control structure where the code executes repeatedly based on a given boolean condition. It's similar to a repeating if statement. One key difference is that a do...while loop guarantees that the code block will execute at least once, regardless of whether the co
4 min read
JS Perfomance & Debugging
JS Object
Objects in JavascriptAn object in JavaScript is a data structure used to store related data collections. It stores data as key-value pairs, where each key is a unique identifier for the associated value. Objects are dynamic, which means the properties can be added, modified, or deleted at runtime.There are two primary w
4 min read
Object Oriented Programming in JavaScriptObject Oriented Programming (OOP) is a style of programming that uses classes and objects to model real-world things like data and behavior. A class is a blueprint that defines the properties and methods an object can have, while an object is a specific instance created from that class. Why OOP is N
3 min read
JavaScript ObjectsIn our previous article on Introduction to Object Oriented Programming in JavaScript we have seen all the common OOP terminology and got to know how they do or don't exist in JavaScript. In this article, objects are discussed in detail.Creating Objects:In JavaScript, Objects can be created using two
6 min read
Creating objects in JavaScriptAn object in JavaScript is a collection of key-value pairs, where keys are strings (properties) and values can be any data type. Objects can be created using object literals, constructors, or classes. Properties are defined with key-value pairs, and methods are functions defined within the object, e
5 min read
JavaScript JSON ObjectsJSON (JavaScript Object Notation) is a handy way to share data. It's easy for both people and computers to understand. In JavaScript, JSON helps organize data into simple objects. Let's explore how JSON works and why it's so useful for exchanging information.const jsonData = { "key1" : "value1", ...
3 min read
JavaScript Object ReferenceJavaScript Objects are the most important data type and form the building blocks for modern JavaScript. The "Object" class represents the JavaScript data types. Objects are quite different from JavaScriptâs primitive data types (Number, String, Boolean, null, undefined, and symbol). It is used to st
4 min read
JS Function
Functions in JavaScriptFunctions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs.JavaScriptfunction sum(x, y) { return x + y; } console.log(sum(6, 9)); // output: 15Function Syntax
4 min read
How to write a function in JavaScript ?JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
4 min read
JavaScript Function CallThe call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). This allows borrowing methods from other objects, executing them within a different context, overriding the default value, and passing arguments. Syntax: cal
2 min read
Different ways of writing functions in JavaScriptA JavaScript function is a block of code designed to perform a specific task. Functions are only executed when they are called (or "invoked"). JavaScript provides different ways to define functions, each with its own syntax and use case.Below are the ways of writing functions in JavaScript:Table of
3 min read
Difference between Methods and Functions in JavaScriptGrasping the difference between methods and functions in JavaScript is essential for developers at all levels. While both are fundamental to writing effective code, they serve different purposes and are used in various contexts. This article breaks down the key distinctions between methods and funct
3 min read
Explain the Different Function States in JavaScriptIn JavaScript, we can create functions in many different ways according to the need for the specific operation. For example, sometimes we need asynchronous functions or synchronous functions. Â In this article, we will discuss the difference between the function Person( ) { }, let person = Person ( )
3 min read
JavaScript Function Complete ReferenceA JavaScript function is a set of statements that takes inputs, performs specific computations, and produces outputs. Essentially, a function performs tasks or computations and then returns the result to the user.Syntax:function functionName(Parameter1, Parameter2, ..) { // Function body}Example: Be
3 min read
JS Array
JavaScript ArraysIn JavaScript, an array is an ordered list of values. Each value, known as an element, is assigned a numeric position in the array called its index. The indexing starts at 0, so the first element is at position 0, the second at position 1, and so on. Arrays can hold any type of dataâsuch as numbers,
7 min read
JavaScript Array MethodsTo help you perform common tasks efficiently, JavaScript provides a wide variety of array methods. These methods allow you to add, remove, find, and transform array elements with ease.Javascript Arrays Methods1. JavaScript Array length The length property of an array returns the number of elements i
7 min read
Best-Known JavaScript Array MethodsAn array is a special variable in all programming languages used to store multiple elements. JavaScript array come with built-in methods that every developer should know how to use. These methods help in adding, removing, iterating, or manipulating data as per requirements.There are some Basic JavaS
6 min read
Important Array Methods of JavaScriptJavaScript arrays are powerful tools for managing collections of data. They come with a wide range of built-in methods that allow developers to manipulate, transform, and interact with array elements.Some of the most important array methods in JavaScript areTable of Content1. JavaScript push() Metho
7 min read
JavaScript Array ReferenceJavaScript Array is used to store multiple elements in a single variable. It can hold various data types, including numbers, strings, objects, and even other arrays. It is often used when we want to store a list of elements and access them by a single variable.Syntax:const arr = ["Item1", "Item2", "
4 min read