Have four indexes: top, down, left and right which are
gonna be used to point where we are gonna start printing rows and
columns.
When
top > down OR left > right then we are DONE!!!!!
public class MultiDimSpiralPrint {
public static void main(String[] args) {
int[][] i = {
{1, 2, 3},
{4, 5 , 6},
{7, 8, 9},
};
spiralOrder(i);
}
static void spiralOrder(int[][] matrix)
{
if(matrix.length == 0)
return;
// Initialize our four indexes
int top = 0;
int down = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
while(true)
{
// Print top row
for(int j = left; j <= right; ++j) System.out.print(matrix[top][j] + " ");
top++;
if(top > down || left > right) break;
//Print the rightmost column
for(int i = top; i <= down; ++i) System.out.print(matrix[i][right] + " ");
right--;
if(top > down || left > right) break;
//Print the bottom row
for(int j = right; j >= left; --j) System.out.print(matrix[down][j] + " ");
down--;
if(top > down || left > right) break;
//Print the leftmost column
for(int i = down; i >= top; --i) System.out.print(matrix[i][left] + " ");
left++;
if(top > down || left > right) break;
}
}
}
OUTPUT
1 2 3 6 9 8 7 4 5
NON SPIRAL PRINT is Easy
int[][] i = {
{1, 2, 3},
{4, 5 , 6},
{7, 8, 9},
};
for ( int[] inner : i) {
for ( int result : inner) {
System.out.println(result);
}
}
OUTPUT 1 2 3 4 5 6 7 8 9
When
top > down OR left > right then we are DONE!!!!!
public class MultiDimSpiralPrint {
public static void main(String[] args) {
int[][] i = {
{1, 2, 3},
{4, 5 , 6},
{7, 8, 9},
};
spiralOrder(i);
}
static void spiralOrder(int[][] matrix)
{
if(matrix.length == 0)
return;
// Initialize our four indexes
int top = 0;
int down = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
while(true)
{
// Print top row
for(int j = left; j <= right; ++j) System.out.print(matrix[top][j] + " ");
top++;
if(top > down || left > right) break;
//Print the rightmost column
for(int i = top; i <= down; ++i) System.out.print(matrix[i][right] + " ");
right--;
if(top > down || left > right) break;
//Print the bottom row
for(int j = right; j >= left; --j) System.out.print(matrix[down][j] + " ");
down--;
if(top > down || left > right) break;
//Print the leftmost column
for(int i = down; i >= top; --i) System.out.print(matrix[i][left] + " ");
left++;
if(top > down || left > right) break;
}
}
}
OUTPUT
1 2 3 6 9 8 7 4 5
NON SPIRAL PRINT is Easy
int[][] i = {
{1, 2, 3},
{4, 5 , 6},
{7, 8, 9},
};
for ( int[] inner : i) {
for ( int result : inner) {
System.out.println(result);
}
}
OUTPUT 1 2 3 4 5 6 7 8 9
0 comments:
Post a Comment