本帖最后由 蓝色骨头 于 2013-4-9 20:25 编辑
试着写了一个思路如下:
四个顶点确定一层,每次顺时针处理一层。
螺旋矩阵最后剩下一行、一竖、一点、或没有。
代码:
public class Test {
/*
* 四个顶点确定一层,每次顺时针处理一层。
* 螺旋矩阵最后剩下一行、一竖、一点、或没有。
*/
public static int[][] spiralMatrix(int m, int n){
if(m < 1 || n < 1){
return null;
}
class Point{
Point(int x, int y){
this.x = x;
this.y = y;
}
int x,y;
}
int[][] matrix = new int[m][n];
//four point
Point topLeft = new Point(0,0);
Point topRight = new Point(0,n-1);
Point bottomLeft = new Point(m-1,0);
Point bottomRight = new Point(m-1,n-1);
int count = 0;
while((topRight.y - topLeft.y >= 1) && (bottomLeft.x - topLeft.x >= 1)){
//clockwise
for(int i = topLeft.y; i <= topRight.y; i++){
matrix[topLeft.x] = ++count;
}
for(int i = topRight.x + 1; i <= bottomRight.x - 1; i++ ){
matrix[topRight.y] = ++count;
}
for(int i = bottomRight.y; i >= bottomLeft.y; i--){
matrix[bottomRight.x] = ++count;
}
for(int i = bottomLeft.x - 1; i >= topLeft.x + 1; i--){
matrix[bottomLeft.y] = ++count;
}
topLeft.x++; topLeft.y++;
topRight.x++; topRight.y--;
bottomLeft.x--; bottomLeft.y++;
bottomRight.x--; bottomRight.y--;
}
//a line(horizontal or vertical) or a point or nothing left
if(topRight.y - topLeft.y >= 1){
for(int i = topLeft.y; i <= topRight.y; i++){
matrix[topLeft.x] = ++count;
}
}else if(bottomLeft.x - topLeft.x >= 1){
for(int i = topLeft.x; i <= bottomLeft.x; i++){
matrix[topLeft.y] = ++count;
}
}else if(topLeft.x == topRight.x && topLeft.y == topRight.y && topLeft.x == topLeft.y){
matrix[topLeft.x][topLeft.y] = ++count;
}
return matrix;
}
public static void printMatrix(int[][] matrix, int m, int n){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
System.out.format("%3d",matrix[j]);
}
System.out.println();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] matrix = null;
int m = 9;
int n = 9;
matrix = spiralMatrix(m, n);
printMatrix(matrix, m, n);
}
}
|