A matrix will be in M x N format.So what we need to do is, get value of indexes from 0,0 to m,n.
Itreate the two dimensional array in spiral mode as follow
TraverseMatrixSpiral.java
- we need to traverse matrix and remove the row/column which already traversed.
- We are not going to delete the elements instead we will limit it by defining boundaries.
- Boundaries can be t, b, l, r we need to specify the direction variable dir. It decides the direction of traverse as below. dir=0; ->right, dir=1 -> down, dir=2 -> left, dir=3 ->up
TraverseMatrixSpiral.java
package com.sk.iwq.matrix;
public class TraverseMatrixSpiral {
private static final int M = 3;
private static final int N = 3;
public static void main(String[] args) {
TraverseMatrixSpiral app = new TraverseMatrixSpiral();
int matrix[][] = app.createMatrix();
app.printMatrix(matrix);
System.out.println(app.traverseSpriral(matrix).toString());
}
private StringBuilder traverseSpriral(int[][] matrix) {
StringBuilder sb = new StringBuilder();
int dir = 0;
int t = 0;
int b = M - 1;
int l = 0;
int r = N - 1;
while (t <= b && l <= r) {
if (dir == 0) {
for (int i = l; i <= r; i++) {
sb.append(matrix[t][i] + ", ");
}
t++;
}
if (dir == 1) {
for (int i = t; i <= b; i++) {
sb.append(matrix[i][r] + ", ");
}
r--;
}
if (dir == 2) {
for (int i = r; i >= l; i--) {
sb.append(matrix[b][i] + ", ");
}
b--;
}
if (dir == 3) {
for (int i = b; i <= t; i++) {
sb.append(matrix[i][l] + ", ");
}
l++;
}
dir = (dir + 1) % 4;
}
return sb;
}
private int[][] createMatrix() {
int matrix[][] = new int[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = (int) (Math.random() * 100 + 1);
}
}
return matrix;
}
private void printMatrix(int[][] matrix) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
System.out.print(matrix[i][j]);
System.out.print(" ");
}
System.out.println(" ");
}
}
}
/*
****** SAMPLE INPUT ********
50 36 22
31 88 87
27 73 95
******* INPUT ********
****** SAMPLE OUTPUT ********
50, 36, 22, 87, 95, 73, 27, 31, 88
******* OUTPUT ********
*/
No comments:
Post a Comment