结果
顺时针
01 02 03 04
10 11 12 05
09 08 07 06
逆时针
04 03 02 01
05 12 11 10
06 07 08 09
代码
public class test {
public test() {
}
private static int[][] data = null;
private int datai = 1; //数值
private static int h =0, i=0, j;
private int row1 =0,col1 =0,row2=0,col2=0;
static int x=3,y=4; // x=? y=?
public static void main(String[] args)
{
j = y-1;
data = new int[x][y]; //data init 定义了x行 y列的矩阵 用于存放数据
test t = new test();
t.input(1); //开始数据塞入 1表示 从左到右
//数据输出
System.out.println("顺时针");
for (int ki=0;ki {
for (int kj=0;kj {
System.out.print(addZero(String.valueOf(x*y).length(),data[ki][kj])+" ");
}
System.out.println("");
}
System.out.println("逆时针");
int[][] kk = niuniu(data,x,y); //矩阵倒置
for (int ki=0;ki {
for (int kj=0;kj {
System.out.print(addZero(String.valueOf(x*y).length(),kk[ki][kj])+" ");
}
System.out.println("");
}
}
private void input(int typej)
{
if (datai > x*y)
{
//System.out.println("exit");如果数据塞入到头 退出递归
}
else
{
//从左到右塞入数据
if (typej == 1) {
for (int k = i; k <= j; k++) {
data[h][k] = datai++;
}
row1++; //上面走了一行
h = y - 1 - col1; //下一步从上到下表示的列值
i = row1; //行起始
j = x - 1 - col1; //行终止
input(2); //从上到下遍历数据
}
//从上到下塞入数据
if ( typej == 2) {
for (int k = i; k <= j; k++) {
data[k][h] = datai++;
}
col1++; //左边走了一列
h = x - 1 - row2; //下一步从右到左表示的行值
i = y - 1 - col1; //列起始
j = col2; //列终止
input(3); //从右到左遍历数据
}
//从右到左塞入数据
if ( typej == 3) {
for (int k = i; k >= j; k--) {
data[h][k] = datai++;
}
row2++; //下面走了一行
h = col2; //下一步从下到上表示的列值
i = x - 1 - row2; //行起始
j = row1; //行终止
input(4); //从下到上遍历数据
}
//从下到上塞入数据
if (typej == 4) {
for (int k = i; k >= j; k--) {
data[k][h] = datai++;
}
col2++; //左面走了一列
h = row1; //下一步从左到右的行值
i = col2; //列起始
j = y - 1 - col1; //列终止
input(1);
}
}
}
//补位
public static String addZero(int weishu, int num) {
/* int num=new Integer(num).intValue();*/
int len = Integer.toString(num).length();
if (len >= weishu) {
return Integer.toString(num);
}
int i = 0;
int j = weishu - len;
String BH = "";
while (i < j) {
BH = "0" + BH;
i = i + 1;
}
BH = BH + Integer.toString(num);
return BH;
}
//列copy,第1列和最后一列互换 依次类推
public static int[][] niuniu(int[][] temp,int xi,int yi)
{
int[][] rs = new int[xi][yi];
int foxi = yi/2;
for (int i=0;i {
for (int j=0;j {
rs[j][yi-1-i] = temp[j][i];
}
}
int col = foxi-1;
int k = 0;
if (yi%2 == 0)
{
k = foxi;
}
else
{
k = foxi +1;
}
for (int i=k;i<=yi-1;i++)
{
for (int j=0;j {
rs[j][col] = temp[j][i];
}
col--;
}
if (yi%2 == 0)
{
}
else
{
for (int j=0;j {
rs[j][foxi] = temp[j][foxi];
}
}
return rs;
}
}