有一个矩阵,用序列沿边缘循环填充,例如指定行5,列3,则输出序列如下:
1 2 3
12 13 4
11 14 5
10 15 6
9 8 7
主要是状态之间的切换,注意切换的条件以及终止条件即可,Java代码实现如下:
public class OuterLoopMatrix {
private int row = 1;
private int col = 1;
private int[][] matrix = null;
private enum Direction{
RIGHT,DOWN,UP,LEFT
}
private Direction dir;
/**
* Constructor
* @param row
* @param col
*/
public OuterLoopMatrix(int row , int col){
if(row < 0 && col < 0){
this.row = 1;
this.col = 1;
System.out.println("row and col must be greater than 0");
}
this.row = row;
this.col = col;
this.matrix = new int[row][col];
this.dir = Direction.RIGHT;
}
/**
* print the matrix
*/
public void printMatrix(){
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(matrix[i][j]);
System.out.print(" ");
}
System.out.println();
}
}
/**
* generate the matrix
*/
public void genMatrix(){
int count=1;
int cr=0;
int cc=0;
// state machine
while(count <= col * row){
switch (this.dir) {
case RIGHT:
if(cc < col && matrix[cr][cc] == 0){
matrix[cr][cc]=count;
cc++;
count++;
}
else{
cc--;
this.dir = Direction.DOWN;
cr++;
}
break;
case DOWN:
if(cr < row && matrix[cr][cc] == 0){
matrix[cr][cc]=count;
cr++;
count++;
}
else{
cr--;
this.dir = Direction.LEFT;
cc--;
}
break;
case LEFT:
if(cc >=0 && matrix[cr][cc] == 0){
matrix[cr][cc]=count;
cc--;
count++;
}
else{
cc++;
this.dir = Direction.UP;
cr--;
}
break;
case UP:
if(cr >=0 && matrix[cr][cc] == 0){
matrix[cr][cc]=count;
cr--;
count++;
}
else{
cr++;
this.dir = Direction.RIGHT;
cc++;
}
break;
default:
break;
}
}
}
}