Given an M * N matrix, print the elements in a clockwise spiral manner. Return an array with the elements in the order of their appearance when printed in a spiral manner.
Input: matrix = [[1, 2, 3], [4 ,5 ,6], [7, 8, 9]]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Explanation: The elements in the spiral order are 1, 2, 3 -> 6, 9 -> 8, 7 -> 4, 5
Input: matrix = [[1, 2, 3, 4], [5, 6, 7, 8]]
Output: [1, 2, 3, 4, 8, 7, 6, 5]
Explanation: The elements in the spiral order are 1, 2, 3, 4 -> 8, 7, 6, 5
Input: matrix = [[1, 2], [3, 4], [5, 6], [7, 8]]
The idea is to use four separate loops to print the array elements in spiral. 1st loop will print the elements from left to right. 2nd loop will print the elements from top to bottom. 3rd loop will print the elements from right to left. 4th loop will print the elements from bottom to top.
top
as 0, left
as 0, bottom
as TotalRow - 1, right
as ToatalColumn - 1.
top
is less than or equal to bottom
and left
less than or equal to right
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
//Function to print matrix in spiral manner.
vector<int> spiralOrder(vector<vector<int>>& matrix) {
// Define ans vector to store the result
vector<int> ans;
// Number of rows
int n = matrix.size();
// Number of columns
int m = matrix[0].size();
// Initialize pointers for traversal
int top = 0, left = 0;
int bottom = n - 1, right = m - 1;
// Traverse the matrix in spiral order
while (top <= bottom && left <= right) {
// Traverse from left to right
for (int i = left; i <= right; ++i) {
ans.push_back(matrix[top][i]);
}
top++;
// Traverse from top to bottom
for (int i = top; i <= bottom; ++i) {
ans.push_back(matrix[i][right]);
}
right--;
// Traverse from right to left
if (top <= bottom) {
for (int i = right; i >= left; --i) {
ans.push_back(matrix[bottom][i]);
}
bottom--;
}
// Traverse from bottom to top
if (left <= right) {
for (int i = bottom; i >= top; --i) {
ans.push_back(matrix[i][left]);
}
left++;
}
}
//Return the ans
return ans;
}
};
int main() {
vector<vector<int>> mat = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
// Create an instance of the Solution class
Solution finder;
// Get spiral order using class method
vector<int> ans = finder.spiralOrder(mat);
cout << "Elements in spiral order are: ";
for (int i = 0; i < ans.size(); ++i) {
cout << ans[i] << " ";
}
cout << endl;
return 0;
}
import java.util.*;
class Solution {
//Function to print matrix in spiral manner
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<>();
// Number of rows
int n = matrix.length;
// Number of columns
int m = matrix[0].length;
// Initialize pointers for traversal
int top = 0, left = 0;
int bottom = n - 1, right = m - 1;
// Traverse the matrix in spiral order
while (top <= bottom && left <= right) {
// Traverse from left to right
for (int i = left; i <= right; ++i) {
ans.add(matrix[top][i]);
}
top++;
// Traverse from top to bottom
for (int i = top; i <= bottom; ++i) {
ans.add(matrix[i][right]);
}
right--;
// Traverse from right to left
if (top <= bottom) {
for (int i = right; i >= left; --i) {
ans.add(matrix[bottom][i]);
}
bottom--;
}
// Traverse from bottom to top
if (left <= right) {
for (int i = bottom; i >= top; --i) {
ans.add(matrix[i][left]);
}
left++;
}
}
//Return the ans
return ans;
}
public static void main(String[] args) {
int[][] mat = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
// Create an instance of the Solution class
Solution finder = new Solution();
// Get spiral order using class method
List<Integer> ans = finder.spiralOrder(mat);
System.out.print("Elements in spiral order are: ");
for (int i = 0; i < ans.size(); ++i) {
System.out.print(ans.get(i) + " ");
}
System.out.println();
}
}
from typing import List
class Solution:
# Function to print matrix in spiral manner
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
ans = []
# Number of rows
n = len(matrix)
# Number of columns
m = len(matrix[0])
# Initialize pointers for traversal
top, left = 0, 0
bottom, right = n - 1, m - 1
# Traverse the matrix in spiral order
while top <= bottom and left <= right:
# Traverse from left to right
for i in range(left, right + 1):
ans.append(matrix[top][i])
top += 1
# Traverse from top to bottom
for i in range(top, bottom + 1):
ans.append(matrix[i][right])
right -= 1
# Traverse from right to left
if top <= bottom:
for i in range(right, left - 1, -1):
ans.append(matrix[bottom][i])
bottom -= 1
# Traverse from bottom to top
if left <= right:
for i in range(bottom, top - 1, -1):
ans.append(matrix[i][left])
left += 1
#Return the ans
return ans
# Test the solution
if __name__ == "__main__":
mat = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
# Create an instance of the Solution class
finder = Solution()
# Get spiral order using class method
ans = finder.spiralOrder(mat)
print("Elements in spiral order are:", ans)
class Solution {
//Function to print matrix in spiral manner
spiralOrder(matrix) {
let ans = [];
// Number of rows
let n = matrix.length;
// Number of columns
let m = matrix[0].length;
// Initialize pointers for traversal
let top = 0, left = 0;
let bottom = n - 1, right = m - 1;
// Traverse the matrix in spiral order
while (top <= bottom && left <= right) {
// Traverse from left to right
for (let i = left; i <= right; ++i) {
ans.push(matrix[top][i]);
}
top++;
// Traverse from top to bottom
for (let i = top; i <= bottom; ++i) {
ans.push(matrix[i][right]);
}
right--;
// Traverse from right to left
if (top <= bottom) {
for (let i = right; i >= left; --i) {
ans.push(matrix[bottom][i]);
}
bottom--;
}
// Traverse from bottom to top
if (left <= right) {
for (let i = bottom; i >= top; --i) {
ans.push(matrix[i][left]);
}
left++;
}
}
//Return the ans
return ans;
}
}
// Test the solution
let mat = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
];
// Create an instance of the Solution class
let finder = new Solution();
// Get spiral order using class method
let ans = finder.spiralOrder(mat);
console.log("Elements in spiral order are:", ans.join(" "));
Q: How does the algorithm avoid revisiting elements?
A: After traversing a boundary, adjust it inward: Increment top after traversing the top row. Decrement right after traversing the right column. Decrement bottom after traversing the bottom row. Increment left after traversing the left column.
Q: How do I handle the center element in an odd-dimensional matrix?
A: In an odd-dimensional square matrix, the center element is visited during the last iteration. No special handling is needed as the shrinking boundaries naturally include it in the traversal.
Q: How would you handle a sparse matrix?
A: For sparse matrices: Use a coordinate-based approach to track only non-zero elements. Perform the traversal using the coordinates of active elements instead of iterating through every cell.
Q: How would you modify the algorithm for counterclockwise spiral traversal?
A: To traverse counterclockwise:Start with the left column (top to bottom). Traverse the bottom row (right to left). Traverse the right column (bottom to top). Traverse the top row (left to right).