Guest User

Untitled

a guest
Mar 17th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. func spiralOrder(matrix [][]int) []int {
  2. totalColumn := len(matrix)
  3. if totalColumn == 0 {
  4. return make([]int, 0)
  5. }
  6. totalRows := len(matrix[0])
  7.  
  8. resultSlice := make([]int, totalColumn*totalRows)
  9.  
  10. currentIndex := 0
  11. swirlOnce := func(cStartIndex int, cEndIndex int, rStartIndex int, rEndIndex int, appendSlice *[]int) bool {
  12.  
  13. for i := rStartIndex; i <= rEndIndex; i++ {
  14. (*appendSlice)[currentIndex] = matrix[cStartIndex][i]
  15. currentIndex += 1
  16. }
  17.  
  18. if cStartIndex+1 > cEndIndex {
  19. return false
  20. }
  21.  
  22. //down
  23. for i := cStartIndex + 1; i <= cEndIndex; i++ {
  24. (*appendSlice)[currentIndex] = matrix[i][rEndIndex]
  25. currentIndex += 1
  26. }
  27.  
  28. if rEndIndex-1 < rStartIndex {
  29. return false
  30. }
  31.  
  32. //left
  33. for i := rEndIndex - 1; i >= rStartIndex; i-- {
  34. (*appendSlice)[currentIndex] = matrix[cEndIndex][i]
  35. currentIndex += 1
  36. }
  37.  
  38. if cEndIndex-1 <= cStartIndex {
  39. return false
  40. }
  41.  
  42. //up
  43. for i := cEndIndex - 1; i > cStartIndex; i-- {
  44. (*appendSlice)[currentIndex] = matrix[i][rStartIndex]
  45. currentIndex += 1
  46. }
  47. return true
  48. }
  49.  
  50. totalSwirlCount := totalRows / 2
  51. if totalSwirlCount*2 != totalRows {
  52. totalSwirlCount += 1
  53. }
  54.  
  55. for i := 0; i < totalSwirlCount; i++ {
  56. hasNext := swirlOnce(i, totalColumn-1-i, i, totalRows-1-i, &resultSlice)
  57. if !hasNext {
  58. break
  59. }
  60.  
  61. }
  62. return resultSlice
  63. }
Add Comment
Please, Sign In to add comment