顺时针旋转打印数组

顺时针打印矩阵

http://www.nowcoder.com/questionTerminal/9b4c81a02cd34f76be2659fa0d54342a

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 
 * @param matrix int整型二维数组 
 * @return int整型一维数组
*/
func printMatrix( matrix [][]int ) []int {
    // write code here
    if len(matrix)==0 || len(matrix[0])== 0 {
        return nil
    }
    res := []int{}
    return Print(res,matrix,0,0,len(matrix)-1,len(matrix[0])-1)
}
// 存贮对角线的坐标,进行旋转
func Print(res []int,matrix [][]int,row1,col1,row2,col2 int) []int{
    curR,curC := row1,col1
    if ((col1-col2)>0 || (row1-row2) >0){
        return res
    }
    if row1 == row2{
        for i:=col1;i<=col2;i++{
            res = append(res, matrix[row2][i])
        }
        return res
    }else if col1==col2{
        for i:= row1;i<=row2;i++{
            res = append(res, matrix[i][col1])
        }
        return res
    }
    for curC<col2{
        res = append(res, matrix[curR][curC])
        curC++
    }
    for curR < row2{
        res = append(res, matrix[curR][curC])
        curR++
    }
    for curC>col1{
        res = append(res, matrix[curR][curC])
        curC--
    }
    for curR > row1{
        res = append(res, matrix[curR][curC])
        curR--
    }
    return Print(res,matrix,row1+1,col1+1,row2-1,col2-1)
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务