龙空技术网

螺旋矩阵

小猿陪学 413

前言:

现时咱们对“c语言螺旋矩阵”大概比较关怀,姐妹们都想要分析一些“c语言螺旋矩阵”的相关知识。那么小编也在网摘上网罗了一些对于“c语言螺旋矩阵””的相关文章,希望你们能喜欢,大家快快来了解一下吧!

题目:

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

说明:

m == matrix.length

n == matrix[i].length

1 <= m, n <= 10

-100 <= matrix[i][j] <= 100

示例:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]输出:[1,2,3,6,9,8,7,4,5]

思路:

右->下->左->上的顺序遍历,遍历过程中标记已访问过的元素。

代码:

class Solution {public:    vector<int> spiralOrder(vector<vector<int>>& matrix) {        vector<int> result;        //右、下、左、上        int dir[] = {0, 1, 2, 3};        int m = matrix.size();        int n = matrix[0].size();        int i=0, j=-1;        int curr_dir_idx = 0;        int fail_count = 0;        int next_i =i, next_j = j;        while(true){             switch(dir[curr_dir_idx])            {                case 0:                    next_i = i;                    next_j = j+1;                    break;                                    case 1:                    next_i = i+1;                    next_j = j;                    break;                case 2:                    next_i = i;                    next_j = j-1;                    break;                case 3:                    next_i = i-1;                    next_j = j;                    break;            }            if (next_i>=0 && next_i < m && 			    next_j>=0 && next_j < n && 			    matrix[next_i][next_j] != INT_MIN)            {                result.push_back(matrix[next_i][next_j]);                matrix[next_i][next_j] = INT_MIN;                fail_count = 0;                i = next_i;                j = next_j;                       }            else            {                curr_dir_idx =  (curr_dir_idx+1)%4;                fail_count++;                if(fail_count >= 2)                    break;             }        }        return result;    }};

标签: #c语言螺旋矩阵