|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 2684. Maximum Number of Moves in a Grid |
| 4 | +# https://leetcode.com/problems/maximum-number-of-moves-in-a-grid |
| 5 | +# Medium |
| 6 | + |
| 7 | +=begin |
| 8 | +You are given a 0-indexed m x n matrix grid consisting of positive integers. |
| 9 | +You can start at any cell in the first column of the matrix, and traverse the grid in the following way: |
| 10 | +* From a cell (row, col), you can move to any of the cells: (row - 1, col + 1), (row, col + 1) and (row + 1, col + 1) such that the value of the cell you move to, should be strictly bigger than the value of the current cell. |
| 11 | +Return the maximum number of moves that you can perform. |
| 12 | +
|
| 13 | +Example 1: |
| 14 | +Input: grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]] |
| 15 | +Output: 3 |
| 16 | +Explanation: We can start at the cell (0, 0) and make the following moves: |
| 17 | +- (0, 0) -> (0, 1). |
| 18 | +- (0, 1) -> (1, 2). |
| 19 | +- (1, 2) -> (2, 3). |
| 20 | +It can be shown that it is the maximum number of moves that can be made. |
| 21 | +
|
| 22 | +Example 2: |
| 23 | +Input: grid = [[3,2,4],[2,1,9],[1,1,7]] |
| 24 | +Output: 0 |
| 25 | +Explanation: Starting from any cell in the first column we cannot perform any moves. |
| 26 | +
|
| 27 | +Constraints: |
| 28 | +* m == grid.length |
| 29 | +* n == grid[i].length |
| 30 | +* 2 <= m, n <= 1000 |
| 31 | +* 4 <= m * n <= 105 |
| 32 | +* 1 <= grid[i][j] <= 106 |
| 33 | +=end |
| 34 | + |
| 35 | +# @param {Integer[][]} grid |
| 36 | +# @return {Integer} |
| 37 | +def max_moves(grid) |
| 38 | + steps = Array.new(grid[0].size) { |i| [i, []] }.to_h |
| 39 | + steps[0] = grid.count.times.to_a |
| 40 | + |
| 41 | + grid[0].size.times.drop(1).each do |col| |
| 42 | + grid.count.times do |row| |
| 43 | + steps[col] << row if (steps[col - 1] & [row - 1, row, row + 1]).any? { |r| grid.dig(r, col - 1).to_i < grid.dig(row, col) } |
| 44 | + end |
| 45 | + break if steps[col].empty? |
| 46 | + end |
| 47 | + |
| 48 | + steps.count { |(_, v)| v.any? } - 1 |
| 49 | +end |
| 50 | + |
| 51 | +# **************** # |
| 52 | +# TEST # |
| 53 | +# **************** # |
| 54 | + |
| 55 | +require "test/unit" |
| 56 | +class Test_max_moves < Test::Unit::TestCase |
| 57 | + def test_ |
| 58 | + assert_equal 3, max_moves([[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]]) |
| 59 | + assert_equal 0, max_moves([[3,2,4],[2,1,9],[1,1,7]]) |
| 60 | + end |
| 61 | +end |
0 commit comments