4ms O(n) Java Counting Sort (計數排序) Solution
The max distance is R + C, and the result array\'s length is R * C. Since the distance is limited (generally, compared with the cell count), we can use Counting
The max distance is `R + C`, and the result array\'s length is `R * C`. Since the distance is limited (generally, compared with the cell count), we can use Counting Sort (\u8A08\u6578\u6392\u5E8F) to solve it efficiently.\n\nTime complexity is `O(R * C)`, i.e. `O(n)`.\n\n> **66 / 66** test cases passed.\n> **Status**: Accepted\n> **Runtime**: 4 ms\n> **Memory Usage**: 38.5 MB\n\n```java\nclass Solution {\n    public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {\n        int[] counter = new int[R + C + 1];\n        for (int r = 0; r < R; r++) {\n            for (int c = 0; c < C; c++) {\n                int dist = Math.abs(r - r0) + Math.abs(c - c0);\n                counter[dist + 1] += 1;\n            }\n        }\n        \n        for (int i = 1; i < counter.length; i++) {\n            counter[i] += counter[i - 1];\n        }\n        \n        int[][] ans = new int[R * C][];\n        for (int r = 0; r < R; r++) {\n            for (int c = 0; c < C; c++) {\n                int dist = Math.abs(r - r0) + Math.abs(c - c0);\n                ans[counter[dist]] = new int[] { r, c };\n                counter[dist]++;\n            }\n        }\n        \n        return ans;\n    }\n}\n```
[]