Thursday, October 31, 2013

How to Solve Spiral Problem

My solution for spiral problem.
package main

import (
    "fmt"
)

func spiral(height, width, row, col int) []int {
    a := createSlice(height, width)
    result := []int{}
    r := row - 1
    c := col - 1
    result = append(result, a[r][c])
    x := 1
    for z := 0; (height * width) != len(result); z++ {
        for i := 0; i < x; i++ {
            r, c = up(r, c)
            if !outOfBoundary(height, width, r, c) {
                result = append(result, a[r][c])
            }
        }
        for i := 0; i < x; i++ {
            r, c = left(r, c)
            if !outOfBoundary(height, width, r, c) {
                result = append(result, a[r][c])
            }
        }
        x += 1
        for i := 0; i < x; i++ {
            r, c = down(r, c)
            if !outOfBoundary(height, width, r, c) {
                result = append(result, a[r][c])
            }
        }
        for i := 0; i < x; i++ {
            r, c = right(r, c)
            if !outOfBoundary(height, width, r, c) {
                result = append(result, a[r][c])
            }
        }
        x += 1
    }
    return result
}

func outOfBoundary(height, width, row, col int) bool {
    return !((row >= 0 && row < height) && (col >= 0 && col < width))
}

func left(row, col int) (int, int) {
    return row, col - 1
}

func right(row, col int) (int, int) {
    return row, col + 1
}

func up(row, col int) (int, int) {
    return row - 1, col
}

func down(row, col int) (int, int) {
    return row + 1, col
}

func createSlice(height, width int) [][]int {
    a := make([][]int, height)
    n := 1
    for i := 0; i < height; i++ {
        a[i] = make([]int, width)
        for j := 0; j < width; j++ {
            a[i][j] = n
            n += 1
        }
    }
    return a
}

func main() {
    fmt.Println(spiral(5, 5, 3, 3))
    fmt.Println(spiral(2, 4, 1, 2))
    fmt.Println(spiral(5, 5, 4, 2))
}

No comments:

Post a Comment