Advertisement
teknoraver

Spiral Matrix IV

Sep 9th, 2024 (edited)
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.06 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * type ListNode struct {
  4.  *     Val int
  5.  *     Next *ListNode
  6.  * }
  7.  */
  8.  
  9. func next(head *ListNode) (*ListNode, int) {
  10.     if head != nil {
  11.         val := head.Val
  12.         return head.Next, val
  13.     }
  14.     return nil, -1
  15. }
  16.  
  17. func fillBorder(m1, m2, n1, n2 int, head *ListNode, matrix [][]int) {
  18.     // North
  19.     if n2-n1 < 1 || m2-m1 < 1 {
  20.         return
  21.     }
  22.     for i := n1; i < n2; i++ {
  23.         head, matrix[m1][i] = next(head)
  24.     }
  25.  
  26.     // East
  27.     if m2-m1 < 1 {
  28.         return
  29.     }
  30.     for j := m1 + 1; j < m2; j++ {
  31.         head, matrix[j][n2-1] = next(head)
  32.     }
  33.  
  34.     // South
  35.     if n2-n1 <= 1 || m2-m1 <= 1 {
  36.         return
  37.     }
  38.     for i := n2 - 2; i >= n1; i-- {
  39.         head, matrix[m2-1][i] = next(head)
  40.     }
  41.  
  42.     // West
  43.     if m2-m1 <= 1 {
  44.         return
  45.     }
  46.     for j := m2 - 2; j > m1; j-- {
  47.         head, matrix[j][m1] = next(head)
  48.     }
  49.     fillBorder(m1+1, m2-1, n1+1, n2-1, head, matrix)
  50. }
  51.  
  52. func spiralMatrix(m int, n int, head *ListNode) [][]int {
  53.     matrix := make([][]int, m)
  54.     for i, _ := range matrix {
  55.         matrix[i] = make([]int, n)
  56.     }
  57.  
  58.     fillBorder(0, m, 0, n, head, matrix)
  59.  
  60.     return matrix
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement