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:
- Input: box = [["#",".","#"]]
- Output: [["."], ["#"], ["#"]]
Example 2:
- Input: box = [["#",".","","."], ["#","#","","."]]
- Output: [["#","."], ["#","#"], ["",""], [".","."]]
Example 3:
- Input: box = [["#","#","",".","","."], ["#","#","#","*",".","."], ["#","#","#",".","#","."]]
- Output: [[".","#","#"], [".","#","#"], ["#","#",""], ["#","","."], ["#",".","*"], ["#",".","."]]
Constraints:
- m == box.length
- n == box[i].length
- 1
- box[i][j] is either '#', '*', or '.'.
Hint:
- Rotate the box using the relation rotatedBox[i][j] = box[m - 1 - j][i].
- 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:
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.
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:
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.
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:
- Create a new matrix for the rotated box.
- Iterate through each column of the rotated matrix (after rotation).
- Simulate gravity for each column by starting from the bottom and moving upwards. Place stones ('#') as far down as possible, leaving obstacles ('*') in place.
- 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:
-
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.
-
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
- Gravity simulation: O(m x n), as we iterate through each element in the matrix.
- 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:
- GitHub
The above is the detailed content of Rotating the Box. For more information, please follow other related articles on the PHP Chinese website!

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

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

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

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.

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

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.

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.

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


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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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
God-level code editing software (SublimeText3)

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
