Spiral Matrix IV
2326. Spiral Matrix IV
Difficulty: Medium
Topics: Array, Linked List, Matrix, Simulation
You are given two integers m and n, which represent the dimensions of a matrix.
You are also given the head of a linked list of integers.
Generate an m x n matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining empty spaces, fill them with -1.
Return the generated matrix.
Example 1:
- Input: m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0]
- Output: [[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]]
-
Explanation:
- The diagram above shows how the values are printed in the matrix.
- Note that the remaining spaces in the matrix are filled with -1.
Example 2:
- Input: m = 1, n = 4, head = [0,1,2]
- Output: [[0,1,2,-1]]
-
Explanation:
- The diagram above shows how the values are printed from left to right in the matrix.
- The last space in the matrix is set to -1.
Example 3:
- Input: cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]
- Output: 10
Constraints:
- 1 <= m, n <= 105
- 1 <= m, n <= 105
- The number of nodes in the list is in the range [1, m * n].
- 0 <= Node.val <= 1000
Hint:
- First, generate an m x n matrix filled with -1s.
- Navigate within the matrix at (i, j) with the help of a direction vector ⟨di, dj⟩. At (i, j), you need to decide if you can keep going in the current direction.
- If you cannot keep going, rotate the direction vector clockwise by 90 degrees.
Solution:
We will simulate a spiral traversal of an m x n matrix, filling it with values from a linked list. The remaining positions that don't have corresponding linked list values will be filled with -1.
Here's how the solution is structured:
- Matrix Initialization: We first create an m x n matrix initialized with -1.
- Direction Vectors: The spiral movement can be controlled using a direction vector that cycles through the right, down, left, and up directions. This ensures that we are traversing the matrix in a spiral manner.
- Linked List Iteration: We traverse through the linked list, placing values in the matrix in spiral order.
- Boundary Handling: We check if we've reached the boundary or encountered an already filled cell. If so, we change direction (clockwise).
Let's implement this solution in PHP: 2326. Spiral Matrix IV
val = $val; $this->next = $next; } } /** * @param Integer $m * @param Integer $n * @param ListNode $head * @return Integer[][] */ function spiralMatrix($m, $n, $head) { ... ... ... /** * go to ./solution.php */ } // Helper function to print the matrix (for debugging) function printMatrix($matrix) { foreach ($matrix as $row) { echo implode(" ", $row) . "\n"; } } // Example usage: // Create the linked list: [3,0,2,6,8,1,7,9,4,2,5,5,0] $head = new ListNode(3); $head->next = new ListNode(0); $head->next->next = new ListNode(2); $head->next->next->next = new ListNode(6); $head->next->next->next->next = new ListNode(8); $head->next->next->next->next->next = new ListNode(1); $head->next->next->next->next->next->next = new ListNode(7); $head->next->next->next->next->next->next->next = new ListNode(9); $head->next->next->next->next->next->next->next->next = new ListNode(4); $head->next->next->next->next->next->next->next->next->next = new ListNode(2); $head->next->next->next->next->next->next->next->next->next->next = new ListNode(5); $head->next->next->next->next->next->next->next->next->next->next->next = new ListNode(5); $head->next->next->next->next->next->next->next->next->next->next->next->next = new ListNode(0); $m = 3; $n = 5; $matrix = spiralMatrix($m, $n, $head); printMatrix($matrix); ?>Explanation:
Matrix Initialization: The matrix is initialized with -1 so that any unfilled spaces will remain -1 by default.
Spiral Movement:
- The direction vector dirs manages movement in four directions: right, down, left, and up.
- The index dirIndex keeps track of the current direction. After moving in one direction, we calculate the next position and check if it's valid. If not, we change the direction.
Linked List Traversal:
- We traverse through the linked list nodes, placing values in the matrix one by one, following the spiral order.
Boundary and Direction Change:
- When we encounter an invalid position (out of bounds or already filled), we rotate the direction by 90 degrees (i.e., change the direction vector).
Time Complexity:
- Filling the matrix takes O(m * n) because we are traversing every cell once. Hence, the time complexity is O(m * n), which is efficient given the constraints.
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:
- GitHub
The above is the detailed content of Spiral Matrix IV. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

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,

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? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

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 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...

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.

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�...
