WEB开发网
开发学院软件开发Java java实现的Matrix的螺旋排序 阅读

java实现的Matrix的螺旋排序

 2009-09-16 00:00:00 来源:WEB开发网   
核心提示:package Matrix;import java.util.ArrayList;import java.util.Collections;import java.util.List;public class TestMatrix {public static void main(String[] args) {Te

package Matrix;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestMatrix {
 
 public static void main(String[] args) {
  TestMatrix tm = new TestMatrix();
  Integer[][] matrix = tm.sortMatrix(4);
  for (int i = 0; i < 4; i++) {
   for (int j = 0; j < matrix[i].length; j++) {
    System.out.print(matrix[i][j]+",");
   }
   System.out.println();
  }
 }
 
 
 Integer[][] sortMatrix(int x)
 {
  Integer[] temp = new Integer[]{2,4,1,3,5,6,7,8,9,10,12,11,13,14,15};
  List numList = new ArrayList();
  Collections.addAll(numList, temp);
  Collections.sort(numList);
  Integer[][] numMatrix = new Integer[x][x];
  getMatrix(x, numList, numMatrix, 0, 0, 0);
  
  minusZero(numMatrix);
  return numMatrix;
 }
 
 
 void minusZero(Integer[][] numMatrix)
 {
  for (int i = 0; i <numMatrix.length; i++) {
   for (int j = 0; j < numMatrix[i].length; j++) {
    if(numMatrix[i][j] == null)
    {
     numMatrix[i][j] = 0;
    }
   }
  }
 }
 
 void getMatrix(int x, List numList, Integer[][] numMatrix, int list_index, int rowNum, int colNum)
 {
  int col_b = colNum+1;
  int row_r = x - 2;
  int col_u = x - 1;
  for (int i = list_index; i < numList.size(); i++) {
   if(i < numMatrix.length*numMatrix.length)
   {
    if(rowNum < x)
    {
     numMatrix[rowNum][colNum] = (Integer) numList.get(i);
     rowNum++;
    }
    else if(rowNum >= x && col_b < x)
    {
     numMatrix[rowNum-1][col_b] = (Integer) numList.get(i);
     col_b++;
    }
    else if(rowNum >= x && col_b >= x && row_r >= 0)
    {
     numMatrix[row_r][x-1] = (Integer) numList.get(i);
     row_r--;
     if(row_r < 0)
     {
      continue;
     }
    }
    else if (rowNum >= x && col_b >= x && row_r < 0 && col_u > 1)
    {
     numMatrix[colNum][col_u-1] = (Integer) numList.get(i);
     col_u--;
    }
    else
    {
     list_index = i;
     colNum++;
     rowNum = colNum;
     x = x - 1;
     if(colNum < 2)
     {
       getMatrix(x, numList, numMatrix, list_index, rowNum, colNum);
       break;
      
     }
     
    }
   }
  }
 }
 
}

结果如下

1,12,11,10,
2,13,0,9,
3,14,15,8,
4,5,6,7,

如果矩阵数大于list的数,以0补上。

写的不好,请各位看官不要见笑!

如果有更好的方法,请贴出来,让我学习一下。谢谢

Tags:java 实现 Matrix

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接