-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2326_spiral_matrix_iv.rb
More file actions
42 lines (34 loc) · 910 Bytes
/
2326_spiral_matrix_iv.rb
File metadata and controls
42 lines (34 loc) · 910 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# frozen_string_literal: true
# https://leetcode.com/problems/spiral-matrix-iv/
# @param {Integer} m
# @param {Integer} n
# @param {ListNode} head
# @return {Integer[][]}
def spiral_matrix(m, n, head)
matrix = ::Array.new(m) { ::Array.new(n, -1) }
return matrix unless head
directions = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0]
]
current_dir = 0
row = 0
col = 0
current = head
while current
matrix[row][col] = current.val
current = current.next
next_row = row + directions[current_dir][0]
next_col = col + directions[current_dir][1]
if next_row.negative? || next_row >= m || next_col.negative? || next_col >= n || matrix[next_row][next_col] != -1
current_dir = (current_dir + 1) % 4
next_row = row + directions[current_dir][0]
next_col = col + directions[current_dir][1]
end
row = next_row
col = next_col
end
matrix
end