Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func spiralOrder(matrix [][]int) []int {
- totalColumn := len(matrix)
- if totalColumn == 0 {
- return make([]int, 0)
- }
- totalRows := len(matrix[0])
- resultSlice := make([]int, totalColumn*totalRows)
- currentIndex := 0
- swirlOnce := func(cStartIndex int, cEndIndex int, rStartIndex int, rEndIndex int, appendSlice *[]int) bool {
- for i := rStartIndex; i <= rEndIndex; i++ {
- (*appendSlice)[currentIndex] = matrix[cStartIndex][i]
- currentIndex += 1
- }
- if cStartIndex+1 > cEndIndex {
- return false
- }
- //down
- for i := cStartIndex + 1; i <= cEndIndex; i++ {
- (*appendSlice)[currentIndex] = matrix[i][rEndIndex]
- currentIndex += 1
- }
- if rEndIndex-1 < rStartIndex {
- return false
- }
- //left
- for i := rEndIndex - 1; i >= rStartIndex; i-- {
- (*appendSlice)[currentIndex] = matrix[cEndIndex][i]
- currentIndex += 1
- }
- if cEndIndex-1 <= cStartIndex {
- return false
- }
- //up
- for i := cEndIndex - 1; i > cStartIndex; i-- {
- (*appendSlice)[currentIndex] = matrix[i][rStartIndex]
- currentIndex += 1
- }
- return true
- }
- totalSwirlCount := totalRows / 2
- if totalSwirlCount*2 != totalRows {
- totalSwirlCount += 1
- }
- for i := 0; i < totalSwirlCount; i++ {
- hasNext := swirlOnce(i, totalColumn-1-i, i, totalRows-1-i, &resultSlice)
- if !hasNext {
- break
- }
- }
- return resultSlice
- }
Add Comment
Please, Sign In to add comment