Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,7 @@
| 2697 | Lexicographically Smallest Palindrome | [Ruby](./algorithms/ruby/2697-lexicographically-smallest-palindrome.rb) | Easy |
| 2707 | Extra Characters in a String | [Ruby](./algorithms/ruby/2707-extra-characters-in-a-string.rb) | Medium |
| 2742 | Painting the Walls | [Ruby](./algorithms/ruby/2742-painting-the-walls.rb) | Hard |
| 2849 | Determine if a Cell Is Reachable at a Given Time | [Ruby](./algorithms/ruby/2849-determine-if-a-cell-is-reachable-at-a-given-time) | Medium |

### Database
| # | Title | Solution | Difficulty |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# frozen_string_literal: true

# 2849. Determine if a Cell Is Reachable at a Given Time
# Medium
# https://leetcode.com/problems/determine-if-a-cell-is-reachable-at-a-given-time

=begin
You are given four integers sx, sy, fx, fy, and a non-negative integer t.
In an infinite 2D grid, you start at the cell (sx, sy). Each second, you must move to any of its adjacent cells.
Return true if you can reach cell (fx, fy) after exactly t seconds, or false otherwise.
A cell's adjacent cells are the 8 cells around it that share at least one corner with it. You can visit the same cell several times.

Example 1:
Input: sx = 2, sy = 4, fx = 7, fy = 7, t = 6
Output: true
Explanation: Starting at cell (2, 4), we can reach cell (7, 7) in exactly 6 seconds by going through the cells depicted in the picture above.

Example 2:
Input: sx = 3, sy = 1, fx = 7, fy = 3, t = 3
Output: false
Explanation: Starting at cell (3, 1), it takes at least 4 seconds to reach cell (7, 3) by going through the cells depicted in the picture above. Hence, we cannot reach cell (7, 3) at the third second.

Constraints:
* 1 <= sx, sy, fx, fy <= 109
* 0 <= t <= 109
=end

# @param {Integer} sx
# @param {Integer} sy
# @param {Integer} fx
# @param {Integer} fy
# @param {Integer} t
# @return {Boolean}
def is_reachable_at_time(sx, sy, fx, fy, t)
return false if t == 1 && sx == fx && sy == fy

(sx - fx).abs <= t && (sy - fy).abs <= t
end

# **************** #
# TEST #
# **************** #

require "test/unit"
class Test_is_reachable_at_time < Test::Unit::TestCase
def test_
assert_equal true, is_reachable_at_time(2, 4, 7, 7, 6)
assert_equal false, is_reachable_at_time(3, 1, 7, 3, 3)
end
end