Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Create Spiral-matrix.js #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 17, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions LeetcodeProblems/Spiral-matrix.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
https://leetcode.com/problems/spiral-matrix/description/

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:

Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
*/

/**
* @param {number[][]} matrix
* @return {number[]}
*/

var spiralOrder = function(matrix) {
if(matrix.length === 0)
return [];
var retArray = [];
const rowLength = matrix.length;
const colLength = matrix[0].length;
const countRectangles = Math.ceil(Math.min(colLength, rowLength)/2)
for(var i = 0; i < countRectangles; i++) {
printRect(matrix, i, rowLength, colLength, retArray);
}
return retArray;
};

var printRect = function(matrix, i, rowLength, colLength, retArray) {
const firstRow = i;
const firstCol = i;
const lastRow = rowLength - i - 1;
const lastCol = colLength - i - 1;

for(var col = firstCol; col <= lastCol; col++) {
retArray.push(matrix[firstRow][col]);
}
for(var row = firstRow + 1; row <= lastRow; row++) {
retArray.push(matrix[row][lastCol]);
}
if(firstRow === lastRow || firstCol === lastCol) {
return;
}
for(var col = lastCol - 1; col >= firstCol; col--) {
retArray.push(matrix[lastRow][col]);
}
for(var row = lastRow - 1; row > firstRow; row--) {
retArray.push(matrix[row][firstCol]);
}
}

var main = function() {
const matrix = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]

console.log(spiralOrder(matrix));
}

main();
module.exports.main = main;