Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Leetcode 54: spiral matrix - Febuary 5,2018 mock interview as an interviewer
import java.io.*;
import java.util.*;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
*/
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example, Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
dr = new int[]{0, 1, 0, -1}
dc = new int[]{1, 0, -1, 0}
class Solution {
public static void main(String[] args) {
}
int[] printMatrix(int[][] m) {
int nRows = m.length;
if (nRows < 1) return new int[0];
int nCols = m[0].length;
int[] result = new int[nRows * nCols];
int iRowBegin = 0;
int iColBegin = 0;
int iRowEnd = nRows - 1;
int iColEnd = nCols - 1;
int iR = 0;
while (true) { // whole one circle
for (int i = iColBegin; i<= iColEnd; i++) {
result[iR++] = m[iRowBegin][i];
}
iRowBegin++;
for (int i = iRowBegin; i <= iRowEnd; i++) {
result[iR++] = m[i][iColEnd];
}
iColEnd--;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.