c语言的算法题

n×n的矩阵,采用顺时针打印出1~16.

 

整理自己的算法(c语言):

#include<stdio.h>
#include<stdlib.h>
#define n 4

static int num[n][n];

int canSet(int i, int j){
 if(i<0||i>=n||j<0||j>=n||num[i][j]!=0){
  return 0;
 } else {
  return 1;
 }
}
int main(){
 int i=0,j=0,number=2;
 int a,b;
 num[i][j]=1;
 for(;number<=n*n;number++){
  if(canSet(i,j+1)&&!canSet(i-1, j)){
   j++;
   num[i][j] = number;
   continue;
  }
  if(canSet(i+1, j)&&!canSet(i,j+1)){
   i++;
   num[i][j] = number;
   continue;
  }
  if(canSet(i,j-1)&&!canSet(i+1, j)){
   j--;
   num[i][j] = number;
   continue;
  }
  if(canSet(i-1,j)&&!canSet(i, j-1)){
   i--;
   num[i][j] = number;
   continue;
  }
 }
 for(a=0;a<n;a++){
  for(b=0;b<n;b++){
   printf("%d\t",num[a][b]);
  }
  printf("\n");
 }
 return 0;
}

 

 

 
备注: 这个算法可以改变 n 的值,可以变成 n*n的;
    #define n 4 //可以改动为你需要的n*n阶的
 
如有其他算法,可以交流!
 
posted @ 2012-05-05 15:27  竹青+  阅读(472)  评论(1)    收藏  举报