-
Notifications
You must be signed in to change notification settings - Fork 2
feat(algorithms, matrices): meeting point #179
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| # Best Meeting Point | ||
|
|
||
| You are given a 2D grid of size m×n, where each cell contains either a 0 or a 1. A 1 represents the home of a friend, | ||
| and a 0 represents an empty space. | ||
|
|
||
| Your task is to return the minimum total travel distance to a meeting point. The total travel distance is the sum of the | ||
| Manhattan distances between each friend’s home and the meeting point. | ||
|
|
||
| The **Manhattan Distance** between two points `(x1, y1)` and `(x2, y2)` is calculated as: | ||
| `|x2 - x1| + |y2 - y1|`. | ||
|
|
||
| ## Constraints | ||
|
|
||
| - m == grid.length | ||
| - n == grid[i].length | ||
| - 1 ≤ m, n ≤ 50 | ||
| - `grid[i][j]` is either 0 or 1. | ||
| - There will be at least two friends in the grid. | ||
|
|
||
| ## Examples | ||
|
|
||
|  | ||
|  | ||
|  | ||
|
|
||
| ## Solution | ||
|
|
||
| The main idea of this algorithm is that the total Manhattan distance is minimized when all friends meet at the median | ||
| position, calculated separately for rows and columns. As Manhattan distance can be split into vertical and horizontal | ||
| components, we collect all the row indices and column indices of the friends and compute the distance to their respective | ||
| medians. As we loop through the grid row-wise and column-wise, the row and column indices are gathered in sorted order | ||
| naturally, so no additional sorting is needed. Finally, a two-pointer approach is used to efficiently compute the total | ||
| distance by pairing positions from both ends toward the center. | ||
|
|
||
| Using the intuition above, we implement the algorithm as follows: | ||
|
|
||
| 1. Create two vectors, `rows` and `cols`, to store all cells’ row and column indexes where `grid[i][j] == 1`. | ||
| 2. Iterate through the grid row by row. For each cell that contains a 1, push the row index `i` into the `rows` vector. | ||
| 3. Iterate through the grid column by column. For each cell that contains a `1`, push the column index j into the `cols` vector. | ||
| 4. Use the helper function getMinDistance(rows) to calculate the total vertical distance to the optimal row (median). | ||
| 5. Use the helper function getMinDistance(cols) to calculate the total horizontal distance to the optimal column (median). | ||
| 6. Return the sum of the two distances as the minimum total travel distance. | ||
|
|
||
| The getMinDistance helper function receives a list of positions, points, and returns the total minimum travel distance | ||
| to the median. The points list contains either row or column indices of friends. As the Manhattan distance is minimized | ||
| at the median, it uses a two-pointer technique as follows: | ||
|
|
||
| - Initialize a variable, distance, with 0 to compute the total distance. | ||
| - Initialize two pointers, i and j, one at the start and the other at the end. | ||
| - Each step adds the difference points[j] - points[i] to the total distance. | ||
| - This process continues until the pointers meet. | ||
| - Returns the total computed distance. | ||
|
|
||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|
|
||
| ### Time Complexity | ||
|
|
||
| The time complexity of the above algorithm is `O(m×n+k)`, where m×n are the dimensions of the grid and k is the number | ||
| of friends (number of 1s in the grid). This is because: | ||
|
|
||
| - O(m×n) to traverse the entire grid and collect row and column indices. | ||
| - O(k) to compute distances in getMinDistance, where k is the number of friends. | ||
|
|
||
| ### Space Complexity | ||
|
|
||
| The algorithm’s space complexity is `O(k)` because we store up to k row indices and k column indices in two separate | ||
| vectors. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| from typing import List | ||
|
|
||
|
|
||
| def min_total_distance(grid: List[List[int]]) -> int: | ||
| rows, cols = [], [] | ||
|
|
||
| # Helper function to calculate total distance to the median | ||
| def get_min_distance(points: List[int]) -> int: | ||
| distance = 0 | ||
| i, j = 0, len(points) - 1 | ||
|
|
||
| # Use two pointers to accumulate distance from both ends toward the center | ||
| while i < j: | ||
| distance += points[j] - points[i] | ||
| i += 1 | ||
| j -= 1 | ||
|
|
||
| return distance | ||
|
|
||
| # Collect all row indices where grid[i][j] == 1 | ||
| for i in range(len(grid)): | ||
| for j in range(len(grid[0])): | ||
| if grid[i][j] == 1: | ||
| rows.append(i) | ||
|
|
||
| # Collect all column indices where grid[i][j] == 1 | ||
| for j in range(len(grid[0])): | ||
| for i in range(len(grid)): | ||
| if grid[i][j] == 1: | ||
| cols.append(j) | ||
|
|
||
| # Compute total vertical and horizontal distances to medians | ||
| return get_min_distance(rows) + get_min_distance(cols) | ||
|
|
||
|
|
||
| def min_total_distance_2(grid: List[List[int]]) -> int: | ||
| """ | ||
| Find the minimum total distance for all people to meet at one point. | ||
| The optimal meeting point is the median of all x-coordinates and y-coordinates. | ||
|
|
||
| Args: | ||
| grid: 2D grid where 1 represents a person's location, 0 represents empty space | ||
|
|
||
| Returns: | ||
| Minimum total Manhattan distance for all people to meet | ||
| """ | ||
|
|
||
| def calculate_distance_sum(positions: List[int], meeting_point: int) -> int: | ||
| """ | ||
| Calculate sum of distances from all positions to the meeting point. | ||
|
|
||
| Args: | ||
| positions: List of coordinate values (either row or column indices) | ||
| meeting_point: The target coordinate to measure distance to | ||
|
|
||
| Returns: | ||
| Sum of absolute distances | ||
| """ | ||
| return sum(abs(position - meeting_point) for position in positions) | ||
|
|
||
| # Collect all row and column indices where people are located | ||
| row_indices = [] | ||
| column_indices = [] | ||
|
|
||
| for row_index, row in enumerate(grid): | ||
| for column_index, cell_value in enumerate(row): | ||
| if cell_value == 1: # Person found at this location | ||
| row_indices.append(row_index) | ||
| column_indices.append(column_index) | ||
|
|
||
| # Sort column indices to find median (row indices already sorted due to iteration order) | ||
| column_indices.sort() | ||
|
|
||
| # Find median positions (optimal meeting point) | ||
| # Using bit shift for integer division by 2 | ||
| median_row = row_indices[len(row_indices) >> 1] | ||
| median_column = column_indices[len(column_indices) >> 1] | ||
|
|
||
| # Calculate total distance as sum of row distances and column distances | ||
| total_distance = calculate_distance_sum( | ||
| row_indices, median_row | ||
| ) + calculate_distance_sum(column_indices, median_column) | ||
|
|
||
| return total_distance |
Binary file added
BIN
+31.7 KB
...thms/matrix/best_meeting_point/images/examples/best_meeting_point_example_1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+27 KB
...thms/matrix/best_meeting_point/images/examples/best_meeting_point_example_2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+32.7 KB
...thms/matrix/best_meeting_point/images/examples/best_meeting_point_example_3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+29.3 KB
...ms/matrix/best_meeting_point/images/solutions/best_meeting_point_solution_1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+37.9 KB
...s/matrix/best_meeting_point/images/solutions/best_meeting_point_solution_10.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+29.8 KB
...s/matrix/best_meeting_point/images/solutions/best_meeting_point_solution_11.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+35.4 KB
...s/matrix/best_meeting_point/images/solutions/best_meeting_point_solution_12.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+30.3 KB
...s/matrix/best_meeting_point/images/solutions/best_meeting_point_solution_13.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+27.7 KB
...ms/matrix/best_meeting_point/images/solutions/best_meeting_point_solution_2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+30.1 KB
...ms/matrix/best_meeting_point/images/solutions/best_meeting_point_solution_3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+37.3 KB
...ms/matrix/best_meeting_point/images/solutions/best_meeting_point_solution_4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+31.8 KB
...ms/matrix/best_meeting_point/images/solutions/best_meeting_point_solution_5.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+30.4 KB
...ms/matrix/best_meeting_point/images/solutions/best_meeting_point_solution_6.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+30.9 KB
...ms/matrix/best_meeting_point/images/solutions/best_meeting_point_solution_7.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+35.3 KB
...ms/matrix/best_meeting_point/images/solutions/best_meeting_point_solution_8.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+26.8 KB
...ms/matrix/best_meeting_point/images/solutions/best_meeting_point_solution_9.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
29 changes: 29 additions & 0 deletions
29
algorithms/matrix/best_meeting_point/test_best_meeting_point.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| import unittest | ||
| from typing import List | ||
| from parameterized import parameterized | ||
| from algorithms.matrix.best_meeting_point import ( | ||
| min_total_distance, | ||
| min_total_distance_2, | ||
| ) | ||
|
|
||
| BEST_MEETING_POINT_TEST_CASES = [ | ||
| ([[1, 0, 0], [0, 0, 0], [0, 0, 1]], 4), | ||
| ([[1, 1]], 1), | ||
| ([[0, 0, 1], [1, 0, 0], [0, 0, 1]], 4), | ||
| ] | ||
|
|
||
|
|
||
| class BestMeetingPointTestCase(unittest.TestCase): | ||
| @parameterized.expand(BEST_MEETING_POINT_TEST_CASES) | ||
| def test_min_total_distance(self, grid: List[List[int]], expected: int): | ||
| actual = min_total_distance(grid) | ||
| self.assertEqual(expected, actual) | ||
|
|
||
| @parameterized.expand(BEST_MEETING_POINT_TEST_CASES) | ||
| def test_min_total_distance_2(self, grid: List[List[int]], expected: int): | ||
| actual = min_total_distance_2(grid) | ||
| self.assertEqual(expected, actual) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.