码迷,mamicode.com
首页 > 其他好文 > 详细

简单螺旋打印矩阵 - 直接, 好理解

时间:2014-10-27 12:44:22      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   sp   div   2014   

打印螺旋矩阵的一种简单办法 , C 语言实现

 

 

#include <stdio.h>

#define N 30
static int val = 10;
int arr[N][N];
void print_row(int row_cur, int col_start, int col_end, int left_to_right){
    int col_cur = col_start;
    if( col_start < 0 || col_end < 0) return;
    if( left_to_right){
        while(col_cur < col_end){
            printf("%d ", arr[row_cur][col_cur]);
            //scanf("%d", &arr[row_cur][col_cur]);
            arr[row_cur][col_cur] = val++;
            ++col_cur;
        }
    }
    else{
        while(col_cur > col_end){
            printf("%d ", arr[row_cur][col_cur]);
            
            arr[row_cur][col_cur] = val++;
            --col_cur;
        }
    }
}
void print_col(int col_cur, int row_start, int row_end, int up_to_bottom){
    int row_cur = row_start;
    if(row_start < 0 || row_end < 0 ) return;
    if(up_to_bottom){
        while(row_cur < row_end){
            printf("%d ", arr[row_cur][col_cur]);
            //scanf("%d", &arr[row_cur][col_cur]);
            arr[row_cur][col_cur] = val++;
            ++row_cur;
        }
    }
    else{
        while(row_cur > row_end){
            printf("%d ", arr[row_cur][col_cur]);
            //scanf("%d", &arr[row_cur][col_cur]);
            arr[row_cur][col_cur] = val++;
            --row_cur;
        }
    }
}
void read_matrix(int row_start, int row_end, int col_start, int col_end){
    if(row_start > row_end|| col_start > col_end)
        return;
    if(row_start == row_end || col_start == col_end)
    {
        printf("%d ", arr[row_start][col_start]);
        //scanf("%d", &arr[row_start][col_start]);
        arr[row_start][col_start] = val++;
        return;
    }
    int i = row_start;
    int j = col_start;
    int i_end = row_end;
    int j_end = col_end;
        print_row(i,       j,        j_end,   1);
        print_col(N-j-1,   i,        i_end,     1);
        print_row(N-i-1,   j_end,    j,    0);
        print_col(j,       i_end,    i, 0);


    read_matrix(row_start+1,   row_end-1, col_start+1, col_end-1);
}
void printf_()
{
    int i, j ;
    i = 0, j = 0;
    while(i < N){
        while(j < N){
            printf("%d ", arr[i][j]);
            ++j;
        }
        printf("\n");
        ++i;
        j = 0;
    }
}



int main(void)
{
    memset(arr, N*N,0);
    read_matrix(0, N-1, 0, N-1);
    getchar();
    printf_();

}

运行结果 :

bubuko.com,布布扣

 

简单螺旋打印矩阵 - 直接, 好理解

标签:style   blog   http   io   color   ar   sp   div   2014   

原文地址:http://www.cnblogs.com/misserwell/p/misserwell-988-my_exec_C.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!