首页 > 代码库 > 简单螺旋打印矩阵 - 直接, 好理解
简单螺旋打印矩阵 - 直接, 好理解
打印螺旋矩阵的一种简单办法 , C 语言实现
#include <stdio.h>#define N 30static 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_();}
运行结果 :
简单螺旋打印矩阵 - 直接, 好理解
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。