LeetCode 1030: Matrix Cells in Distance Order Solution

Master LeetCode problem 1030 (Matrix Cells in Distance Order), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1030. Matrix Cells in Distance Order

Problem Explanation

Explanation:

To solve this problem, we can calculate the distance of each cell in the matrix from the center cell (rCenter, cCenter) using the given formula |r1 - r2| + |c1 - c2|. We then sort the cells based on their distance in ascending order and return the coordinates.

  1. Create a list to store the coordinates of all cells in the matrix.
  2. Iterate over all cells in the matrix and calculate the distance of each cell from the center cell (rCenter, cCenter).
  3. Sort the list of coordinates based on their distances in ascending order.
  4. Return the sorted list of coordinates.

Time Complexity: O(rows * cols * log(rows * cols))
Space Complexity: O(rows * cols)

:

Solution Code

class Solution {
    public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
        int[][] result = new int[rows * cols][2];
        List<int[]> cells = new ArrayList<>();
        
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                cells.add(new int[]{i, j});
            }
        }
        
        Collections.sort(cells, (a, b) -> {
            int distA = Math.abs(a[0] - rCenter) + Math.abs(a[1] - cCenter);
            int distB = Math.abs(b[0] - rCenter) + Math.abs(b[1] - cCenter);
            return distA - distB;
        });
        
        for (int i = 0; i < cells.size(); i++) {
            result[i] = cells.get(i);
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1030 (Matrix Cells in Distance Order)?

This page provides optimized solutions for LeetCode problem 1030 (Matrix Cells in Distance Order) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1030 (Matrix Cells in Distance Order)?

The time complexity for LeetCode 1030 (Matrix Cells in Distance Order) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1030 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1030 in Java, C++, or Python.

Back to LeetCode Solutions