From 835763fe6a2a98169a303572f01c3426704202d1 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 8 Aug 2024 11:11:50 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB885.=20Spiral=20Matrix=20II?= =?UTF-8?q?I=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/spiral-matrix-iii.java | 41 +++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 java/spiral-matrix-iii.java diff --git a/java/spiral-matrix-iii.java b/java/spiral-matrix-iii.java new file mode 100644 index 0000000..34b87a4 --- /dev/null +++ b/java/spiral-matrix-iii.java @@ -0,0 +1,41 @@ +class Solution { + private record Coord(int x, int y) { + public void assign(int[] coord) { + coord[0] = y; + coord[1] = x; + } + + public Coord add(Coord rhs) { + return new Coord(x + rhs.x, y + rhs.y); + } + } + + private static final List DIRECTIONS = + Arrays.asList(new Coord(1, 0), new Coord(0, 1), new Coord(-1, 0), new Coord(0, -1)); + + private boolean inBounds(int rows, int cols, Coord pos) { + return pos.y() >= 0 && pos.y() < rows && pos.x() >= 0 && pos.x() < cols; + } + + public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) { + int[][] matrix = new int[rows * cols][2]; + + var pos = new Coord(cStart, rStart); + for (int i = 0, step = 1, direction = 0; i < matrix.length; ++step) { + for (int j = 0; j < 2; ++j) { + for (int k = 0; k < step; ++k) { + if (inBounds(rows, cols, pos)) { + pos.assign(matrix[i]); + ++i; + } + + pos = pos.add(DIRECTIONS.get(direction)); + } + + direction = (direction + 1) % 4; + } + } + + return matrix; + } +}