Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Leetcode 54 - Spiral matrix - Being an interviewer - February 1, 2018
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
You can’t perform that action at this time.