Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0dc6bb5

Browse files
niuli1991jinbudaily
authored andcommitted
添加59.螺旋矩阵II Ruby实现
1 parent 7aa2a3e commit 0dc6bb5

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

‎problems/0059.螺旋矩阵II.md‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -688,6 +688,58 @@ public class Solution {
688688
}
689689
```
690690

691+
### Ruby#:
692+
```ruby
693+
def generate_matrix(n)
694+
result = Array.new(n) { Array.new(n, 0) }
695+
#循环次数
696+
loop_times = 0
697+
#步长
698+
step = n - 1
699+
val = 1
700+
701+
702+
while loop_times < n / 2
703+
#模拟从左向右
704+
for i in 0..step - 1
705+
#行数不变,列数变
706+
result[loop_times][i+loop_times] = val
707+
val += 1
708+
end
709+
710+
#模拟从上到下
711+
for i in 0..step - 1
712+
#列数不变,行数变
713+
result[i+loop_times][n-loop_times-1] = val
714+
val += 1
715+
end
716+
717+
#模拟从右到左
718+
for i in 0..step - 1
719+
#行数不变,列数变
720+
result[n-loop_times-1][n-loop_times-i-1] = val
721+
val += 1
722+
end
723+
724+
#模拟从下到上
725+
for i in 0..step - 1
726+
#列数不变,行数变
727+
result[n-loop_times-i-1][loop_times] = val
728+
val += 1
729+
end
730+
731+
loop_times += 1
732+
step -= 2
733+
end
734+
735+
#如果是奇数,则填充最后一个元素
736+
result[n/2][n/2] = n**2 if n % 2
737+
738+
return result
739+
740+
end
741+
```
742+
691743
<p align="center">
692744
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
693745
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /