From 1cc7fd0b13aa5cc84c0600fef60f3864311d7d88 Mon Sep 17 00:00:00 2001 From: Fahim Abbasi <63852008+fahamabbasi@users.noreply.github.com> Date: Fri, 15 Oct 2021 16:46:08 +0700 Subject: [PATCH] Create SpiralMatrix.java Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 Explanation: The output is matrix in spiral format. Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Output: 1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 Explanation :The output is matrix in spiral format. --- SpiralMatrix.java | 50 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 SpiralMatrix.java diff --git a/SpiralMatrix.java b/SpiralMatrix.java new file mode 100644 index 0000000..44693b1 --- /dev/null +++ b/SpiralMatrix.java @@ -0,0 +1,50 @@ +import java.util.*; + +class Solution { + + // Function to print in spiral order + public static List spiralOrder(int[][] matrix) + { + List ans = new ArrayList(); + + if (matrix.length == 0) + return ans; + + int R = matrix.length, C = matrix[0].length; + boolean[][] seen = new boolean[R][C]; + int[] dr = { 0, 1, 0, -1 }; + int[] dc = { 1, 0, -1, 0 }; + int r = 0, c = 0, di = 0; + + // Iterate from 0 to R * C - 1 + for (int i = 0; i < R * C; i++) { + ans.add(matrix[r]); + seen[r] = true; + int cr = r + dr[di]; + int cc = c + dc[di]; + + if (0 <= cr && cr < R && 0 <= cc && cc < C + && !seen[cr][cc]) { + r = cr; + c = cc; + } + else { + di = (di + 1) % 4; + r += dr[di]; + c += dc[di]; + } + } + return ans; + } + + // Driver Code + public static void main(String[] args) + { + int a[][] = { { 1, 2, 3, 4 }, + { 5, 6, 7, 8 }, + { 9, 10, 11, 12 }, + { 13, 14, 15, 16 } }; + + System.out.println(spiralOrder(a)); + } +}