Grid Game

Jan 22, 2025 am 02:02 AM

2017. Grid Game

Difficulty: Medium

Topics: Array, Matrix, Prefix Sum

You are given a 0-indexed 2D array grid of size 2 x n, where grid[r][c] represents the number of points at position (r, c) on the matrix. Two robots are playing a game on this matrix.

Both robots initially start at (0, 0) and want to reach (1, n-1). Each robot may only move to the right ((r, c) to (r, c 1)) or down ((r, c) to (r 1, c)).

At the start of the game, the first robot moves from (0, 0) to (1, n-1), collecting all the points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is set to 0. Then, the second robot moves from (0, 0) to (1, n-1), collecting the points on its path. Note that their paths may intersect with one another.

The first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally, return the number of points collected by the second robot.

Example 1:

Grid Game

  • Input: grid = [[2,5,4],[1,5,1]]
  • Output: 4
  • Explanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.
    • The cells visited by the first robot are set to 0.
    • The second robot will collect 0 0 4 0 = 4 points.

Example 2:

Grid Game

  • Input: grid = [[3,3,1],[8,5,2]]
  • Output: 4
  • Explanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.
    • The cells visited by the first robot are set to 0.
    • The second robot will collect 0 3 1 0 = 4 points.

Example 3:

Grid Game

  • Input: grid = [[1,3,1,15],[1,3,3,1]]
  • Output: 7
  • Explanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.
    • The cells visited by the first robot are set to 0.
    • The second robot will collect 0 1 3 3 0 = 7 points.

Constraints:

  • grid.length == 2
  • n == grid[r].length
  • 1 4
  • 1 5

Hint:

  1. There are n choices for when the first robot moves to the second row.
  2. Can we use prefix sums to help solve this problem?

Solution:

We'll use the following approach:

  1. Prefix Sum Calculation: We'll compute the prefix sums for both rows of the grid to efficiently calculate the sum of points for any subarray.

  2. Simulating Optimal Movement:

    • The first robot determines its path to minimize the points left for the second robot.
    • At each column transition, the first robot can choose to move down, splitting the grid into two segments:
      • Upper remaining points: Points in the top row after the transition column.
      • Lower remaining points: Points in the bottom row before the transition column.
  3. Minimizing the Maximum Points for the Second Robot:

    • At each transition, calculate the maximum points the second robot can collect after the first robot's path.
    • Track the minimum of these maximums across all transitions.

Let's implement this solution in PHP: 2017. Grid Game

<?php function gridGame($grid) {
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */
}

// Example usage
$grid1 = [[2, 5, 4], [1, 5, 1]];
$grid2 = [[3, 3, 1], [8, 5, 2]];
$grid3 = [[1, 3, 1, 15], [1, 3, 3, 1]];

echo gridGame($grid1) . "\n"; // Output: 4
echo gridGame($grid2) . "\n"; // Output: 4
echo gridGame($grid3) . "\n"; // Output: 7
?>
Copy after login

Explanation:

  1. Prefix Sum Calculation:

    • prefixTop and prefixBottom store cumulative sums for the top and bottom rows, respectively.
    • These allow efficient range sum calculations.
  2. Simulating the First Robot's Path:

    • At each column i, the first robot can decide to move down after column i.
    • This splits the grid into two regions:
      • Top row after column i (collected points: prefixTop[n] - prefixTop[i 1]).
      • Bottom row before column i (collected points: prefixBottom[i]).
  3. Second Robot's Optimal Points:

    • The second robot will take the maximum of the two remaining regions.
    • We track the minimum of these maximums for all possible transitions.
  4. Complexity:

    • Time Complexity: O(n), as we compute prefix sums and loop through the grid once.
    • Space Complexity: O(n), due to prefix sum arrays.

Example Walkthrough

Input: grid = [[2, 5, 4], [1, 5, 1]]

  • Prefix Sums:
    • prefixTop = [0, 2, 7, 11]
    • prefixBottom = [0, 1, 6, 7]
  • Transition Points:
    • i = 0: Top Remaining = 11 - 7 = 9, Bottom Remaining = 0 → Second Robot = 9.
    • i = 1: Top Remaining = 11 - 11 = 4, Bottom Remaining = 1 → Second Robot = 4.
    • i = 2: Top Remaining = 0, Bottom Remaining = 6 → Second Robot = 6.
  • Minimum Points for Second Robot: min(9, 4, 6) = 4.

This matches the expected output.

Contact Links

If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

  • LinkedIn
  • GitHub

The above is the detailed content of Grid Game. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles