[leetcode-54]Spiral Matrix(C语言)

问题描述:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].

这道题没啥可说的,上代码:

int* spiralOrder(int** matrix, int matrixRowSize, int matrixColSize) {
        int length = matrixRowSize*matrixColSize;
    int *result = (int *)malloc(sizeof(int)*length);
    char *visited = (char *)calloc(length,sizeof(char));//store visited element

    int index = 0;
    int row=0,col=-1;
    while(1){
        if(index == length)
            break;
        for(col=col+1;col<matrixColSize;col++){
            if(visited[row*matrixColSize+col] == 1)         
                break;
            result[index++]=matrix[row][col];
            visited[row*matrixColSize+col] = 1;
        }
        col--;
        for(row = row+1;row<matrixRowSize;row++){
            if(visited[row*matrixColSize+col] == 1)
                break;
            result[index++] = matrix[row][col];
            visited[row*matrixColSize+col] = 1;
        }
        row--;
        for(col = col-1;col>=0;col--){
            if(visited[row*matrixColSize+col] == 1)
                break;
            result[index++] = matrix[row][col];
            visited[row*matrixColSize+col] = 1;
        }
        col++;
        for(row = row-1;row>=0;row--){
            if(visited[row*matrixColSize+col] == 1)         
                break;
            result[index++] = matrix[row][col];
            visited[row*matrixColSize+col] = 1;
        }
        row++;
    }
    return result;
}
阅读更多
文章标签: leetcode 算法
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

[leetcode-54]Spiral Matrix(C语言)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭