c++ | bfs | faster than 94.25% with Explanation
let\'s suppose x (in black) as my starting position, the nearest points with distance = 1 are in red, then if we move to red cells, the nearest cells to them ar
let\'s suppose x (in black) as my starting position, the nearest points with distance = 1 are in red, then if we move to red cells, the nearest cells to them are green cells distance = 1 to reds ans distance = 1 + 1 to black x ... and that\'s the idea to traverse the graph with bfs, don\'t use dfs as it goes in depth and we will losse the order of distance.\n![image](https://assets.leetcode.com/users/images/c293358d-958d-4bcc-bf98-615166b29f9f_1662325600.0550125.png)\n\n```\nconst int N = 102;\nbool vis[N][N];\nint dx[4] = {0, 0, 1, -1};\nint dy[4] = {1, -1, 0, 0};\nint n, m;\nclass Solution {\npublic:\n    bool safe(int i, int j)\n    {\n        return i>-1 && j>-1 && i<n && j<m;    \n    }\n    \n    void bfs(int i, int j, vector<vector<int>> &ans)\n    {\n        queue<pair<int,int>> q;\n        q.push({i, j});\n        vis[i][j] = 1;\n        vector<int> pt(2);\n        pt[0]=i;\n        pt[1]=j;\n        ans.push_back(pt);\n        \n        while(!q.empty())\n        {\n            auto p = q.front();\n            q.pop();\n            int pi = p.first;\n            int pj = p.second;\n            \n            for (int d=0 ; d<4 ; d++)\n            {\n                int ci = pi + dx[d];\n                int cj = pj + dy[d];\n                if (safe(ci, cj) && !vis[ci][cj])\n                {\n                    vis[ci][cj] = 1;\n                    q.push({ci, cj});\n                    pt[0]=ci;\n                    pt[1]=cj;\n                    ans.push_back(pt);\n                }\n            }\n        }\n    }\n    \n    vector<vector<int>> allCellsDistOrder(int r, int c, int x, int y) \n    {\n        memset(vis, 0, sizeof(vis));\n        vector<vector<int>> ans;\n        n=r;\n        m=c;\n        bfs(x, y, ans);\n        return ans;\n    }\n};\n```
['Breadth-First Search', 'Sorting']