#define DOWN
1
#define RIGHT
2
#define UP
3
#define LEFT
4
void ringMatrix(int** M, int N)
{
int i, j, value = 0;
int direction = DOWN;
//元素都初始化为零
for(i = 0; i < N; i++)
for(j = 0; j < N; j++)
M[i][j] = 0;
i = j = 0;
while(true)
{
switch(direction)
{
case DOWN:
for( ; (i < N) && (M[i][j] == 0); i ++)
M[i][j] = (++ value);
if(M[-- i][++ j] != 0)
return;
direction = RIGHT;
break;
case RIGHT:
for( ; (j < N) && (M[i][j] == 0); j ++)
M[i][j] = (++ value);
if(M[-- i][-- j] != 0)
return;
direction = UP;
break;
case UP:
for( ; (i >= 0) && (M[i][j] == 0); i --)
M[i][j] = (++ value);
if(M[++ i][-- j] != 0)
return;
direction = LEFT;
break;
case LEFT:
for( ; (j >= 0) && (M[i][j] == 0); j --)
M[i][j] = (++ value);
if(M[++ i][++ j] != 0)
return;
direction = DOWN;
break;
}
}
}