Created
March 23, 2018 19:42
-
-
Save jianminchen/c16de647f2d921435853c187e1332a02 to your computer and use it in GitHub Desktop.
Leetcode 54: spiral matrix - Febuary 5,2018 mock interview as an interviewer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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