Leetcode 3028. Ant on the Boundary
You’re given the width width
and the height height
of a rectangular grid where the cells are partitioned. An ant starts at the position (x, y)
at time t = 0
and moves in a straight path, bouncing off the boundaries of the grid. The ant moves at a speed of one cell per second.
Given the current position of the ant, determine the coordinates of the ant after t
seconds.
Answer: Yes, when the ant hits a boundary, it bounces back in the opposite direction.
(x, y)
be on the boundary?Answer: Yes, the initial position can be anywhere within the grid including on the boundaries.
t
:
t
guaranteed to be a non-negative integer?Answer: Yes, t
is guaranteed to be a non-negative integer.
Answer: The movements are within the single row or column, and the ant just bounces back and forth, behaving like a 1D motion.
To determine the position of the ant after t
seconds:
width
and back, treating the motion as bouncing at the endpoints.height
and back.(x + t) % (2 * width)
.width
, the ant is on the bounce-back path.(y + t) % (2 * height)
.height
, the ant is on the bounce-back path.#include <iostream>
#include <vector>
std::vector<int> antPosition(int width, int height, int x, int y, int t) {
// Calculate the new coordinates
int x_distance = (x + t) % (2 * width);
int y_distance = (y + t) % (2 * height);
int new_x = (x_distance < width) ? x_distance : (2 * width - x_distance);
int new_y = (y_distance < height) ? y_distance : (2 * height - y_distance);
return {new_x, new_y};
}
int main() {
int width = 5, height = 4;
int x = 1, y = 0, t = 10;
std::vector<int> position = antPosition(width, height, x, y, t);
std::cout << "Position after " << t << " seconds: (" << position[0] << ", " << position[1] << ")" << std::endl;
return 0;
}
O(1)
t
seconds involve basic arithmetic and modulus operations, which are all constant time.O(1)
By following this strategy and implementation, the ant’s new position can be efficiently calculated after any given t
seconds.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?