How to use Simulation Approach In Javascript
- 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); |
Output
1 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).
JavaScript Program to Print Given Matrix in Spiral Form
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]
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]
Table of Content
- Using Boundary Traversal Approach
- Using Simulation Approach
- Using Recursion in JavaScript
- Using Depth First Search (DFS)