[Java Code]2 D配列を時計回りに出力
2055 ワード
package com.coding_sloth;
/**
*
* example: :
* 1 2 3 4 5
* 14 15 16 17 6
* 13 20 19 18 7
* 12 11 10 9 8
* :1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
* Created by on 14-3-28.
*/
public class Clockwise2DArray {
public void test() {
int[][] array = {{1, 2, 3, 4, 5}, {14, 15, 16, 17, 6},
{13, 20, 19, 18, 7}, {12, 11, 10, 9, 8}};
/*
int[][] array = {{1, 2, 3, 4}, {12, 13, 14, 5},
{11, 16, 15, 6}, {10, 9, 8, 7}};
/*
int[][] array = {{1, 2, 3}, {8, 9, 4}, {7, 6, 5}};
*/
int[] result = clockwise2DArray(array, 4, 5);
for(int a : result) {
System.out.print(a + " ");
}
}
//M array ,N
private int[] clockwise2DArray (int[][] array, int M, int N){
int[] result = new int[M*N];
int count = 1; //
int k = 0; //result[]
while(count <= (min(M, N)+1)/2)
{
//
for (int i = count - 1; i < N - count; i ++) {
result[k] = array[count - 1][i];
k ++;
}
//
for (int i = count - 1; i < M - count; i ++) {
result[k] = array[i][N - count];
k++;
}
//
for (int i = N - count; i > count - 1; i --) {
result[k] = array[M - count][i];
k++;
}
//
for (int i = M - count; i > count - 1; i --) {
result[k] = array[i][count - 1];
k++;
}
count ++;
}
/* [ 3*3 ] , ,
* result
*/
if (k < M*N) {
result[k] = array[count - 2][count - 2];
}
return result;
}
private int min(int a, int b) {
return (a>b) ? b : a;
}
}