Skip to content

Commit a93bab6

Browse files
committed
2326
1 parent b016bc7 commit a93bab6

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

2301-2400/2326_spiral_matrix_iv.rb

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Definition for singly-linked list.
2+
# class ListNode
3+
# attr_accessor :val, :next
4+
# def initialize(val = 0, _next = nil)
5+
# @val = val
6+
# @next = _next
7+
# end
8+
# end
9+
# @param {Integer} m
10+
# @param {Integer} n
11+
# @param {ListNode} head
12+
# @return {Integer[][]}
13+
def spiral_matrix(m, n, head)
14+
matrix = Array.new(m) { Array.new(n, -1) }
15+
round = 0
16+
p = head
17+
until p.nil?
18+
# top left -> right
19+
(round..n-round-1).each { |i|
20+
break if p.nil?
21+
matrix[round][i] = p.val
22+
p = p.next
23+
}
24+
# top right -> bot
25+
(round+1..m-round-1).each { |i|
26+
break if p.nil?
27+
matrix[i][n-round-1] = p.val
28+
p = p.next
29+
}
30+
# bot right -> left
31+
(round+1..n-round-1).each { |i|
32+
break if p.nil?
33+
matrix[m-round-1][n-1-i] = p.val
34+
p = p.next
35+
}
36+
# bot left -> top
37+
(round+1..m-round-2).each { |i|
38+
break if p.nil?
39+
matrix[m-1-i][round] = p.val
40+
p = p.next
41+
}
42+
43+
round += 1
44+
end
45+
46+
matrix
47+
end

0 commit comments

Comments
 (0)