# 打印数字矩阵到标准输出。 # 按顺时针方向,从外到内打印矩阵。起点是矩阵的左上角。 class Matrix def initialize(width) @n = 0 @width = width #矩阵的宽度 # 创建二维数组 @square = Array.new(@width) do Array.new(@width, 0) end end # 打印矩阵 def print_matrix @square.each do |line| line.each do |n| printf("%-3d", n) end puts end end # 填充矩阵。 # start 遍历的起点 def fill_in_the_matrix(start) # 结束递归的条件 return if start > (@width-1)/2 #从左到右遍历 start.upto(@width-start-1) do |i| @square[start][i] = @n += 1 end #从上到下遍历 (start+1).upto(@width-start-1) do |i| @square[i][@width-start-1] = @n += 1 end #从右到左遍历 (@width-start-2).downto(start) do |i| @square[@width-start-1][i] = @n += 1 end #从下到上遍历 (@width-start-2).downto(start+1) do |i| @square[i][start] = @n += 1 end fill_in_the_matrix(start+1) end end m = Matrix.new(ARGV[0].to_i) m.fill_in_the_matrix(0) m.print_matrix