Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2206 from niuli1991/master
Browse files Browse the repository at this point in the history
添加0059.螺旋矩阵II Ruby实现
  • Loading branch information
youngyangyang04 committed Jul 26, 2023
2 parents a130dbb + 0ffbe67 commit cbb5bb5
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions problems/0059.螺旋矩阵II.md
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,58 @@ public class Solution {
}
```

### Ruby#:
```ruby
def generate_matrix(n)
result = Array.new(n) { Array.new(n, 0) }
#循环次数
loop_times = 0
#步长
step = n - 1
val = 1


while loop_times < n / 2
#模拟从左向右
for i in 0..step - 1
#行数不变,列数变
result[loop_times][i+loop_times] = val
val += 1
end

#模拟从上到下
for i in 0..step - 1
#列数不变,行数变
result[i+loop_times][n-loop_times-1] = val
val += 1
end

#模拟从右到左
for i in 0..step - 1
#行数不变,列数变
result[n-loop_times-1][n-loop_times-i-1] = val
val += 1
end

#模拟从下到上
for i in 0..step - 1
#列数不变,行数变
result[n-loop_times-i-1][loop_times] = val
val += 1
end

loop_times += 1
step -= 2
end

#如果是奇数,则填充最后一个元素
result[n/2][n/2] = n**2 if n % 2

return result

end
```

<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
Expand Down

0 comments on commit cbb5bb5

Please sign in to comment.