Created
March 23, 2018 19:37
-
-
Save jianminchen/311809b0ced363eb78c9c6ea858cf633 to your computer and use it in GitHub Desktop.
Leetcode 54 - Spiral matrix - Being an interviewer - February 1, 2018
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. | |
*/ | |
class Solution { | |
public static void main(String[] args) { | |
ArrayList<String> strings = new ArrayList<String>(); | |
strings.add("Hello, World!"); | |
strings.add("Welcome to CoderPad."); | |
strings.add("This pad is running Java 8."); | |
for (String string : strings) { | |
System.out.println(string); | |
} | |
} | |
public List<Integer> spiral(int[][] matrix) { | |
List<Integer> results = new ArrayList<Integer>(); | |
if (matrix.length == 0) | |
return results; | |
int rows = matrix.length; | |
int cols = matrix[0].length; | |
boolean[][] visited = new boolean[rows][cols]; | |
int[] dr = {0, 1, 0, -1}; | |
int[] dc = {1, 0, -1, 0}; | |
int i = 0, j = 0; | |
int count = 0; | |
int dir = 0; | |
while (count < m * n) { | |
if (!visited[i][j]) { | |
results.add(matrix[i][j]); | |
visited[i][j] = true; | |
count++; | |
i += dr[dir]; | |
j += dc[dir]; | |
if (i == 0 || j == 0 || i == rows || j == cols) { | |
if (++dir == 3) | |
dir = 0; | |
} | |
} else { | |
if (++dir == 3) | |
dir = 0; | |
} | |
} | |
return results; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment