Advertisement
Guest User

Untitled

a guest
Mar 20th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. /*
  6.  
  7. Print 2-D array in spiral order
  8.  
  9. numbers := [
  10. [2, 4, 6, 8],
  11. [5, 9, 12, 16],
  12. [1, 11, 5, 9],
  13. [3, 2, 1, 8],
  14. ]
  15.  
  16. => 2, 4, 6, 8, 5, 9, 12, 16, 1, 11, 5, 9, 3, 2, 1, 8
  17.  
  18. */
  19.  
  20. func PrintSpiral(list [][]int, rows, cols int) {
  21. // initialize variables
  22. var T, B, L, R, dir int = 0, rows - 1, 0, cols - 1, 0
  23.  
  24. // the top-most must be less than or equal to bottom-most AND the left-most must be less than or equal to right-most
  25. for {
  26. if T >= B || L >= R {
  27. break
  28. }
  29. // 0 - traverse right (going Left to Right)
  30. if dir == 0 {
  31. fmt.Println("going right")
  32. for i := 0; i <= R; i++ {
  33. fmt.Println(list[T][i])
  34. }
  35. T++
  36. dir = 1
  37. }
  38. // 1 - traverse down (going Top to Bottom)
  39. if dir == 1 {
  40. fmt.Println("going down")
  41. for i := T; i <= B; i++ {
  42. fmt.Println(list[i][R])
  43. }
  44. R--
  45. dir = 2
  46. }
  47. // 2 - traverse left
  48. if dir == 2 {
  49. fmt.Println("going left")
  50. for i := R; i >= L; i-- {
  51. //fmt.Println("---> ", R, i)
  52. fmt.Println(list[B][i])
  53. }
  54. B--
  55. dir = 3
  56. }
  57. // 3 - traverse up
  58. if dir == 3 {
  59. for i := B; i >= T; i-- {
  60. fmt.Println("going up")
  61. fmt.Println(list[i][L])
  62. }
  63. L++
  64. dir = 0
  65. }
  66. }
  67.  
  68. fmt.Printf("wooo")
  69. }
  70.  
  71. func main() {
  72. l := [][]int{
  73. {2, 4, 6, 8},
  74. {5, 9, 12, 16},
  75. {1, 11, 5, 9},
  76. {3, 2, 1, 8},
  77. }
  78.  
  79. m := 4 // number of rows
  80. n := 4 // number of columns
  81. PrintSpiral(l, m, n)
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement