LeetCode 2849: Determine if a Cell Is Reachable at a Given Time Solution

Master LeetCode problem 2849 (Determine if a Cell Is Reachable at a Given Time), a medium 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.

2849. Determine if a Cell Is Reachable at a Given Time

Medium

Problem Explanation

Explanation:

To solve this problem, we can use a breadth-first search (BFS) algorithm. We start from the source cell (sx, sy) and explore all possible adjacent cells in each second. We maintain a queue to store the cells to be visited next along with the time taken to reach them.

At each step, we check if we have reached the target cell (fx, fy) and if the time taken matches the given t. If we reach the target cell within the given time, we return true; otherwise, we continue exploring until we exhaust all possibilities or exceed the time limit.

:

Solution Code

class Solution {
    public boolean isReachable(int sx, int sy, int fx, int fy, int t) {
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{sx, sy, 0});
        
        int[][] directions = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
        
        while (!queue.isEmpty()) {
            int[] cell = queue.poll();
            int x = cell[0];
            int y = cell[1];
            int time = cell[2];
            
            if (x == fx && y == fy && time == t) {
                return true;
            }
            
            if (time >= t) {
                continue;
            }
            
            for (int[] dir : directions) {
                int nx = x + dir[0];
                int ny = y + dir[1];
                
                queue.offer(new int[]{nx, ny, time + 1});
            }
        }
        
        return false;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2849 (Determine if a Cell Is Reachable at a Given Time)?

This page provides optimized solutions for LeetCode problem 2849 (Determine if a Cell Is Reachable at a Given Time) 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 2849 (Determine if a Cell Is Reachable at a Given Time)?

The time complexity for LeetCode 2849 (Determine if a Cell Is Reachable at a Given Time) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2849 on DevExCode?

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

Back to LeetCode Solutions