Skip to content

Instantly share code, notes, and snippets.

@BerkeSoysal
Created August 4, 2022 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BerkeSoysal/f0cb531a989527a178f8bd1a73e59928 to your computer and use it in GitHub Desktop.
Save BerkeSoysal/f0cb531a989527a178f8bd1a73e59928 to your computer and use it in GitHub Desktop.
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertTrue;
public class Program {
private static int memoryVertical = 0;
private static int memoryHorizontal = 0;
public static List<Integer> spiralTraverse(int[][] array)
{
memoryVertical = array.length;
memoryHorizontal = array[0].length;
List<Integer> output = new ArrayList<>();
goRight(array, output,0, 0, --memoryHorizontal);
return output;
}
private static void goRight(int[][] array, List<Integer> output, int row, int start, int end)
{
if(start > end) {
return;
}
for(int i=start; i<=end; i++)
{
output.add(array[row][i]);
}
goDown(array, output, end, row+1,--memoryVertical);
}
private static void goDown(int[][] array, List<Integer> output, int column, int start, int end)
{
if(start > end) {
return;
}
for(int i=start; i<=end; i++)
{
output.add(array[i][column]);
}
goLeft(array, output, end, column-1, array[0].length - memoryHorizontal -1);
}
private static void goLeft(int[][] array, List<Integer> output, int row, int start, int end)
{
if(start < end) {
return;
}
for(int i=start; i>=end; i--)
{
output.add(array[row][i]);
}
goUp(array, output, end, row-1,array.length - memoryVertical);
}
private static void goUp(int[][] array, List<Integer> output, int column, int start, int end)
{
if(start < end) {
return;
}
for(int i=start; i>=end; i--)
{
output.add(array[i][column]);
}
goRight(array, output, end, column+1,--memoryHorizontal);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment