search

. Sliding Puzzle

Dec 02, 2024 am 07:39 AM

773. Sliding Puzzle

Difficulty: Hard

Topics: Array, Breadth-First Search, Matrix

On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.

The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].

Given the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.

Example 1:

. Sliding Puzzle

  • Input: board = [[1,2,3],[4,0,5]]
  • Output: 1
  • Explanation: Swap the 0 and the 5 in one move.

Example 2:

. Sliding Puzzle

  • Input: board = [[1,2,3],[5,4,0]]
  • Output: -1
  • Explanation: No number of moves will make the board solved.

Example 3:

. Sliding Puzzle

  • Input: board = [[4,1,2],[5,0,3]]
  • Output: 5
  • Explanation: 5 is the smallest number of moves that solves the board.
    • An example path:
    • After move 0: [[4,1,2],[5,0,3]]
    • After move 1: [[4,1,2],[0,5,3]]
    • After move 2: [[0,1,2],[4,5,3]]
    • After move 3: [[1,0,2],[4,5,3]]
    • After move 4: [[1,2,0],[4,5,3]]
    • After move 5: [[1,2,3],[4,5,0]]

Constraints:

  • board.length == 2
  • board[i].length == 3
  • 0
  • Each value board[i][j] is unique.

Hint:

  1. Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move.

Solution:

We can apply the Breadth-First Search (BFS) algorithm. The idea is to explore all possible configurations of the board starting from the given initial state, one move at a time, until we reach the solved state.

Approach:

  1. Breadth-First Search (BFS):

    • BFS is ideal here because we are looking for the shortest path to the solved state.
    • Each board configuration can be considered a node, and the edges between nodes represent valid moves where the 0 tile is swapped with an adjacent tile.
    • The BFS will explore the board configurations level by level, ensuring that we reach the solved state with the minimum number of moves.
  2. State Representation:

    • We will represent the board as a string (for easier comparison and storage).
    • The solved state is "123450" because it's a linear representation of the board [[1,2,3],[4,5,0]].
  3. State Transitions:

    • From each state, the 0 tile can swap with one of its 4 neighbors (up, down, left, right), if it's within the bounds of the board.
  4. Tracking Visited States:

    • We need to keep track of visited states to avoid cycles and redundant calculations.
  5. Checking for the Solved State:

    • If at any point the board configuration matches the solved state, we return the number of moves it took to get there.
  6. Handling Impossible Cases:

    • If BFS completes and we don't find the solved state, it means it's impossible to solve the puzzle, and we return -1.

Let's implement this solution in PHP: 773. Sliding Puzzle

<?php /**
 * @param Integer[][] $board
 * @return Integer
 */
function slidingPuzzle($board) {
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */
}

// Test cases
$board1 = [[1, 2, 3], [4, 0, 5]];
echo slidingPuzzle($board1);  // Output: 1

$board2 = [[1, 2, 3], [5, 4, 0]];
echo slidingPuzzle($board2);  // Output: -1

$board3 = [[4, 1, 2], [5, 0, 3]];
echo slidingPuzzle($board3);  // Output: 5
?>

Explanation:

  • Initial Setup: We start by converting the 2D board into a 1D string for easier manipulation.
  • BFS Execution: We enqueue the initial state of the board along with the move count (starting from 0). In each BFS iteration, we explore the possible moves (based on the 0 tile's position), swap 0 with adjacent tiles, and enqueue the new states.
  • Visited States: We use a dictionary to keep track of visited board states to avoid revisiting and looping back to the same states.
  • Edge Validation: We check that any move remains within the bounds of the 2x3 grid, especially ensuring no illegal moves that wrap around the grid (such as moving left at the left edge or right at the right edge).
  • Return Result: If we reach the target state, we return the number of moves. If BFS completes and we don’t reach the target, we return -1.

Time Complexity:

  • BFS Complexity: The time complexity of BFS is O(N), where N is the number of unique board states. For this puzzle, there are at most 6! (720) possible configurations.

Space Complexity:

  • The space complexity is also O(N) due to the storage required for the queue and visited states.

This solution should be efficient enough 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:

  • LinkedIn
  • GitHub

The above is the detailed content of . Sliding Puzzle. 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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software