# Leetcode - Spiral Matrix II

violet posted @ Mar 03, 2020 10:12:33 AM in 算法 with tags Algorithm array ruby Golang , 265 阅读

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

```Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
```

Loop  4 directions and fill it.

```func generateMatrix(n int) [][]int {
directions := []string{"right", "down", "left", "up"}
result := make([][]int, n)
for i := 0; i < n; i++ {
result[i] = make([]int, n)
}
rowStart := 0
rowEnd := n
columnStart := 0
columnEnd := n
visited := 1
for (visited - 1) != (n*n) {
for _, d := range directions {
if d == "right" {
for i := columnStart; i < columnEnd; i++ {
result[rowStart][i] = visited
visited++
}
rowStart++
}
if d == "down" {
for i := rowStart; i < rowEnd; i++ {
result[i][columnEnd-1] = visited
visited++
}
columnEnd--
}
if d == "left" {
for i := columnEnd - 1; i >= columnStart; i--{
result[rowEnd - 1][i] = visited
visited++
}
rowEnd--
}
if d == "up" {
for i := rowEnd - 1; i >= rowStart; i-- {
result[i][columnStart] = visited
visited++
}
columnStart++
}
if (rowStart == rowEnd && columnStart == columnEnd) || (visited-1 == n*n) {
break
}
}
if rowStart == rowEnd && columnStart == columnEnd {
break
}
}

return result
}```

```# @param {Integer} n
# @return {Integer[][]}
def generate_matrix(n)
visited = 1
row_start = 0
row_end = n - 1
column_start = 0
column_end = n - 1
directions = ["right", "down", "left", "up"]
grid = Array.new(n){Array.new(n, 0)}

while visited - 1 != n * n
directions.each do |d|
if d == "right"
for i in column_start..column_end
grid[row_start][i] = visited
visited += 1
end
row_start += 1
end
if d == "down"
for i in row_start..row_end
grid[i][column_end] = visited
visited += 1
end
column_end -= 1
end

if d == "left"
i = column_end
while i >= column_start
grid[row_end][i] = visited
visited += 1
i -= 1
end
row_end -= 1
end

if d == "up"
i = row_end
while i >= row_start
grid[i][column_start] = visited
visited += 1
i -= 1
end
column_start += 1
end

break if  visited - 1 == n*n
end
break if visited - 1 == n*n

end

return grid
end```
modelpapers2020.in 说:
May 03, 2023 09:24:20 PM

Board Model Paper 2023 Aspirants who had Registered for the Board 12th Class Exam can Download the Previous Paper When Board Announces the Dates to Download the Question Paper. modelpapers2020.in Board Question Papers will be Provided Very Soon Through Online Mode and all the Applicants Should Visit the Official Page Regularly for More Information Regarding Previous Paper, Examination Date. Check the Below Provided Details for More Information About the Board Model Paper.

(输入验证码)
or Ctrl+Enter