🔥✅Python Easy Solution✅ Beat 87.63% | ✅ With Explanation🔥
PLEASE UPVOTE\n\n\n# Intuition\n\nWhen faced with the task of sorting matrix cells by their distance from a specific cell, the immediate thought is to leverage 
# **PLEASE UPVOTE**\n\n\n# Intuition\n\nWhen faced with the task of sorting matrix cells by their distance from a specific cell, the immediate thought is to leverage the Manhattan distance formula due to its simplicity and relevance in grid-based problems. This problem\'s essence lies not just in calculating distances but also in efficiently organizing the cells according to these distances. Recognizing that the Manhattan distance provides a straightforward way to compare the proximity between any two points on a grid, we can use it to fulfill the sorting requirement.\n\nimage.png\n![image.png](https://assets.leetcode.com/users/images/b182aefc-2e63-4f95-a79e-0b695666eb7d_1711276338.5454068.png)\n\n# Approach\n\n1. **Generate Coordinates**: Create a list of all cell coordinates in the matrix. This is straightforward in a grid where each cell can be represented by a pair of row and column indices.\n   \n2. **Sort by Distance**: Use the Manhattan distance formula to sort these coordinates. The formula, |r1 - r2| + |c1 - c2|, is applied between the center cell `(rCenter, cCenter)` and each cell in the grid. Sorting based on this distance ensures that cells closer to the center are placed before those farther away.\n\n3. **Return Sorted List**: After sorting, the list of cells now respects the order of increasing distance from the center cell. This sorted list is exactly what is needed as output.\n\n# Complexity\n\n- **Time Complexity**: $$O(n \\log n)$$\n\n    - Generating all cell coordinates takes $$O(n)$$ time, where \\(n\\) is the total number of cells in the matrix (`rows * cols`).\n    - Sorting these cells by their distance from the center cell takes $$O(n \\log n)$$ time, as sorting algorithms typically have this complexity.\n\n- **Space Complexity**: $$O(n)$$\n\n    - The space complexity is determined by the storage of all cell coordinates in a list, requiring $$O(n)$$ space, where \\(n\\) is the total number of cells.\n\n# Code\n\n```python\nfrom typing import List\n\nclass Solution:\n    def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:\n        # Generate all cells\n        all_cells = [[r, c] for r in range(rows) for c in range(cols)]\n        \n        # Sort cells by Manhattan distance from (rCenter, cCenter)\n        all_cells.sort(key=lambda x: abs(x[0] - rCenter) + abs(x[1] - cCenter))\n        \n        # Return sorted cells\n        return all_cells\n```\n
['Array', 'Math', 'Matrix', 'Python', 'C++', 'Java', 'Python3']