search

Rotating the Box

Nov 27, 2024 am 09:46 AM

1861. Rotating the Box

Difficulty: Medium

Topics: Array, Two Pointers, Matrix

You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following:

  • A stone '#'
  • A stationary obstacle '*'
  • Empty '.'

The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions.

It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box.

Return an n x m matrix representing the box after the rotation described above.

Example 1:

Rotating the Box

  • Input: box = [["#",".","#"]]
  • Output: [["."], ["#"], ["#"]]

Example 2:

Rotating the Box

  • Input: box = [["#",".","","."], ["#","#","","."]]
  • Output: [["#","."], ["#","#"], ["",""], [".","."]]

Example 3:

Rotating the Box

  • Input: box = [["#","#","",".","","."], ["#","#","#","*",".","."], ["#","#","#",".","#","."]]
  • Output: [[".","#","#"], [".","#","#"], ["#","#",""], ["#","","."], ["#",".","*"], ["#",".","."]]

Constraints:

  • m == box.length
  • n == box[i].length
  • 1
  • box[i][j] is either '#', '*', or '.'.

Hint:

  1. Rotate the box using the relation rotatedBox[i][j] = box[m - 1 - j][i].
  2. Start iterating from the bottom of the box and for each empty cell check if there is any stone above it with no obstacles between them.

Solution:

We need to follow a few distinct steps:

  1. Rotate the box: We first rotate the matrix 90 degrees clockwise. The rotated matrix will have n rows and m columns, where n is the number of columns in the original box, and m is the number of rows.

  2. Gravity effect: After rotating, we need to simulate the effect of gravity. This means that all stones ('#') should "fall" to the bottom of their new column, stopping only when they encounter an obstacle ('*') or another stone ('#').

Approach:

  1. Rotation: After the rotation, the element at position [i][j] in the original matrix will be placed at position [j][m-1-i] in the rotated matrix.

  2. Gravity simulation: We need to process each column from bottom to top. If there is a stone ('#'), it will fall down until it reaches an obstacle or the bottom. If the cell is empty ('.'), it can hold a stone.

Step-by-step explanation:

  1. Create a new matrix for the rotated box.
  2. Iterate through each column of the rotated matrix (after rotation).
  3. Simulate gravity for each column by starting from the bottom and moving upwards. Place stones ('#') as far down as possible, leaving obstacles ('*') in place.
  4. Return the final rotated matrix.

Let's implement this solution in PHP: 1861. Rotating the Box

<?php function rotateTheBox($box) {
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */
}

// Example Usage
$box = [
    ["#", ".", "#"],
];
print_r(rotateTheBox($box));

$box = [
    ["#", ".", "*", "."],
    ["#", "#", "*", "."],
];
print_r(rotateTheBox($box));

$box = [
    ["#", "#", "*", ".", "*", "."],
    ["#", "#", "#", "*", ".", "."],
    ["#", "#", "#", ".", "#", "."],
];
print_r(rotateTheBox($box));
?>

Explanation:

  1. Simulate Gravity:

    • Traverse each row from right to left. Use a pointer (emptySlot) to track where the next stone should fall.
    • If a stone (#) is encountered, move it to the emptySlot, and then decrement emptySlot.
    • If an obstacle (*) is encountered, reset emptySlot to the position just before the obstacle.
  2. Rotate the Matrix:

    • Create a new matrix where the element at [i][j] in the rotated box is taken from [m - 1 - j][i] of the original box.

Example Output

Input:

$box = [
    ["#", ".", "#"],
];

Output:

[
    [".",],
    ["#",],
    ["#",],
]

Input:

$box = [
    ["#", ".", "*", "."],
    ["#", "#", "*", "."],
];

Output:

[
    ["#", "."],
    ["#", "#"],
    ["*", "*"],
    [".", "."],
]

Time Complexity

  1. Gravity simulation: O(m x n), as we iterate through each element in the matrix.
  2. Rotation: O(m x n), as we create the rotated matrix.

Total: O(m x n).

Space Complexity

  • O(m x n) for the rotated matrix.

This solution is efficient and adheres to the constraints of the problem.

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 Rotating the Box. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft