Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,104 questions

40,777 answers

573 users

How to print a given matrix in spiral form with Node.js

1 Answer

0 votes
function PrintMatrixInSpiralForm(matrix) {
    if (matrix == null || matrix.length == 0) {
        return;
    }
    
    let top = 0;
    let bottom = matrix.length - 1;
    let left = 0;
    let right = matrix[0].length - 1;
    
    while (true) {
        if (left > right) {
            break;
        }
        
        // top row
        for (let i = left; i <= right; i++) {
            console.log(matrix[top][i]);
        }
        console.log();
        top++; // next row
        
        // next row
        if (top > bottom) {
            break;
        }
        
        // right column
        for (let i = top; i <= bottom; i++) {
            console.log(matrix[i][right]);
        }
        
        console.log();
        right--; // previous column
            
        // previous column
        if (left > right) {
            break;
        }
        
        // bottom row
        for (let i = right; i >= left; i--) {
            console.log(matrix[bottom][i]);
        }
        console.log();
        bottom--;  // previous row
        
        // previous row
        if (top > bottom) {
            break;
        }
        
        // left column
        for (let i = bottom; i >= top; i--) {
            console.log(matrix[i][left]);
        }
        console.log();
        left++; // next column
    }
}

        
const matrix = [[1, 2, 3, 4, 100], 
                [5, 6, 7, 8, 200], 
                [9, 10, 11, 12, 300], 
                [13, 14, 15, 16, 400]];
        
PrintMatrixInSpiralForm(matrix);





/*
run:

1 
2 
3 
4 

8 
12 
16 

15 
14 
13 

9 
5 

6 
7 

11 

10 

*/

 





answered Sep 14, 2022 by avibootz

Related questions

1 answer 46 views
1 answer 54 views
1 answer 46 views
1 answer 50 views
1 answer 53 views
...