leetcode59

Posted yxlsblog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode59相关的知识,希望对你有一定的参考价值。

题目:

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入:3

输出:

[ [1,2,3],

  [4,5,6],

  [7,8,9]

]

 

解题思路:

参见leetcode54

 

代码1:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<int> v(n,0);
        vector<vector<int>> res(n,v);
        vector<vector<int>> res_flag(n,v);
        int i=0;
        int j=0;
        int have_left = 0;
        int have_right = 0;
        int have_up = 0;
        int have_down = 0;
        string cur_direction = "right";
        for(int num=1;num<=n*n;num++){
            res[i][j] = num;
            res_flag[i][j] = 1;
            if (j - 1 >= 0 && res_flag[i][j - 1] == 0) have_left = 1;
            if (j + 1 < n && res_flag[i][j + 1] == 0) have_right = 1;
            if (i - 1 >= 0 && res_flag[i - 1][j] == 0) have_up = 1;
            if (i + 1 < n && res_flag[i + 1][j] == 0) have_down = 1;
            cur_direction = nextDirection(cur_direction, have_left,have_right,have_up,have_down); 
            if(cur_direction == "left") j--;
            if(cur_direction == "right") j++;
            if(cur_direction == "up") i--;
            if(cur_direction == "down") i++;
            have_left = 0;
            have_right = 0;
            have_up = 0;
            have_down = 0;
        }
        return res;
    }
    string nextDirection(string cur_direction,int have_left,int have_right,int have_up,int have_down){
        if(cur_direction == "left" && have_left == 1) return "left";
        if(cur_direction == "right" && have_right == 1) return "right";
        if(cur_direction == "up" && have_up == 1) return "up";
        if(cur_direction == "down" && have_down == 1) return "down";
        if(have_left == 1) return "left";
        if(have_right == 1) return "right";
        if(have_up == 1) return "up";
        if(have_down == 1) return "down";
        return "nonext";
    }
};

 

代码2:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n, 0));
        int up = 0, down = n - 1, left = 0, right = n - 1, val = 1;
        while (true) {
            for (int j = left; j <= right; ++j) res[up][j] = val++;
            if (++up > down) break;
            for (int i = up; i <= down; ++i) res[i][right] = val++;
            if (--right < left) break;
            for (int j = right; j >= left; --j) res[down][j] = val++;
            if (--down < up) break;
            for (int i = down; i >= up; --i) res[i][left] = val++;
            if (++left > right) break;
        }
        return res;
    }
};

 

 

 



















以上是关于leetcode59的主要内容,如果未能解决你的问题,请参考以下文章

leetcode59

LeetCode:螺旋矩阵||59

Leetcode.1024 视频拼接

Xcode 4.6 的备份代码片段

在代码片段中包含类型转换

LeetCode810. 黑板异或游戏/455. 分发饼干/剑指Offer 53 - I. 在排序数组中查找数字 I/53 - II. 0~n-1中缺失的数字/54. 二叉搜索树的第k大节点(代码片段