Sometimes, while working with Python Matrix, we can have a problem in which we need to extract all the adjacent coordinates of the given coordinate. This kind of problem can have application in many domains such as web development and school programming. Lets discuss certain way in which this task can be performed.
Input : test_tup = (1, 2, 3) Output : [[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 2], [0, 2, 3], [0, 2, 4], [0, 3, 2], [0, 3, 3], [0, 3, 4], [1, 1, 2], [1, 1, 3], [1, 1, 4], [1, 2, 2], [1, 2, 3], [1, 2, 4], [1, 3, 2], [1, 3, 3], [1, 3, 4], [2, 1, 2], [2, 1, 3], [2, 1, 4], [2, 2, 2], [2, 2, 3], [2, 2, 4], [2, 3, 2], [2, 3, 3], [2, 3, 4]] Input : test_tup = (5, 6) Output : [[4, 5], [4, 6], [4, 7], [5, 5], [5, 6], [5, 7], [6, 5], [6, 6], [6, 7]]
Output : The original tuple : (3, 4)
The adjacent Coordinates : [[2, 3], [2, 4], [2, 5], [3, 3], [3, 4], [3, 5], [4, 3], [4, 4], [4, 5]]
We can generate all possible combinations of adjacent coordinates by using itertools.product() function. We need to generate a list of offsets for each dimension, which will be used to calculate adjacent coordinates. For example, for a 2-dimensional coordinate, we need to generate the following offsets: (-1,-1), (-1,0), (-1,1), (0,-1), (0,0), (0,1), (1,-1), (1,0), (1,1). Then, we can use itertools.product() to generate all possible combinations of these offsets and add them to the input coordinate to get all adjacent coordinates.
OutputInput: (1, 2, 3)
Output: [(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 2), (0, 2, 3), (0, 2, 4), (0, 3, 2), (0, 3, 3), (0, 3, 4), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 2, 2), (1, 2, 4), (1, 3, 2), (1, 3, 3), (1, 3, 4), (2, 1, 2), (2, 1, 3), (2, 1, 4), (2, 2, 2), (2, 2, 3), (2, 2, 4), (2, 3, 2), (2, 3, 3), (2, 3, 4)]
Time Complexity: O(3^n), where n is the number of dimensions.
Auxiliary Space: O(3^n), because we need to generate all possible combinations of offsets.