golang顺时针打印矩阵

栏目: Go · 发布时间: 5年前

内容简介:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

package main

import "fmt"

func main() {
    //s := [][]int{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}
    //s := [][]int{{1}, {2}, {3}, {4}}
    //s := [][]int{{1, 2, 3, 4}, {5, 6, 7, 8}}
    s := [][]int{{1, 2}, {5, 6}, {9, 10}, {13, 14}}

    printMatrix(s)
}
func printMatrix(s [][]int) {
    if s == nil {
        fmt.Println("切片为空,无法打印")
    }
    bex, bey := 0, 0
    hang := len(s) - 1
    lie := len(s[0]) - 1
    if hang == 0 {
        for _, v := range s[0] {
            fmt.Println(v)
        }
        return
    }
    if lie == 0 {
        for _, v := range s {
            fmt.Println(v[0])
        }
        return
    }
    for bex <= hang && bey <= lie {
        ax, ay := bex, bey
        for ay < lie {
            fmt.Println(s[ax][ay])
            ay++
        }
        for ax < hang {
            fmt.Println(s[ax][ay])
            ax++
        }
        for ay > bey {
            fmt.Println(s[ax][ay])
            ay--
        }
        for ax > bex {
            fmt.Println(s[ax][ay])
            ax--
        }
        bex++
        bey++
        hang--
        lie--
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Big Java Late Objects

Big Java Late Objects

Horstmann, Cay S. / 2012-2 / 896.00元

The introductory programming course is difficult. Many students fail to succeed or have trouble in the course because they don't understand the material and do not practice programming sufficiently. ......一起来看看 《Big Java Late Objects》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具