LeetCode-1030. 距离顺序排列矩阵单元格

记录下错误,迭代器可能会在对应容器大小变化时失效


思路为BFS
vector拿来当队列使用,一开始没初始化大小,故而迭代器it(队头)可能会在res.push_back后失效
原因应该是vector的size变大后,不得不放弃之前的内存,重新找了一块更大的内存来存储,地址变化了
vector初始化的语法为

vector<vector<int>> res(大小,初始值);
//故而二维的初始化就是
vector<vector<int>> res(所包含的一维数组的个数, vector<int>(其中每一个一维数组的长度, 初始值));
//二维vector的size是其中一维数组的个数,其中每一个一维的vector也同样有个size
//高维的以此类推

初始化后,就不可以push_back了,必须直接对已有的值进行修改

class Solution {
public:
    vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {
        vector<vector<int>> res(R*C, vector<int>(2, 0));//第一个参数可以填变量我是惊喜一波
        int move[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };//四个动作
        bool* visit = new bool[R * C]{ 0 };//初始化
        int cnt=0;
        res[cnt][0] = r0;
        res[cnt++][1] = c0;
        visit[r0 * C + c0] = true;
        vector<vector<int>>::iterator it = res.begin();
        for (; it != res.end(); it++)
        {
            for (int i = 0; i < 4; i++)
            {
                int xnext = (*it)[0] + move[i][0];
                int ynext = (*it)[1] + move[i][1];
                if (xnext < R && xnext >= 0 && ynext < C && ynext >= 0 && !visit[xnext * C + ynext])
                {
                    res[cnt][0] = xnext;
                    res[cnt++][1] = ynext;
                    visit[xnext * C + ynext] = true;
                }
            }
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/lxzbky/p/13994543.html