You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于2D arrays的Tower of Hanoi模块化移盘实现问题求助

Hey there! I see you're working on a Tower of Hanoi project with 2D arrays, and you've got the basics running but are stuck on modular disk movement. Let's break this down and get you sorted!

Modular Approach to Tower of Hanoi Disk Movement with 2D Arrays

The key to keeping your code modular is splitting it into small, single-responsibility methods—each one does one specific job, making your code easier to debug and modify. Let's build out the pieces around your existing setup:

Step 1: Define Your 2D Array Structure

First, let's lock in how your pegs array works:

  • 3 rows (one for each tower peg)
  • numDisks columns (to hold all possible disks)
  • Use 0 as a placeholder for empty slots, and integers (e.g., larger numbers = larger disks) for actual disks

Step 2: Modular Method Breakdown

Here's how to split your code into clean, reusable components:

1. Initialize the Starting Peg State

Create a method to set up the initial tower (all disks on the first peg):

public static int[][] initializePegs(int numDisks) {
    int[][] pegs = new int[3][numDisks];
    // Fill first peg with disks (largest at the bottom)
    for (int i = 0; i < numDisks; i++) {
        pegs[0][i] = numDisks - i;
    }
    // Other pegs default to 0 (empty)
    return pegs;
}

2. Core Disk Movement Logic

This method handles the actual transfer of a single disk between pegs, updates the 2D array, and triggers visualization. It's the backbone of your modular setup:

public static void moveDisk(int fromPeg, int toPeg, int[][] pegs) {
    int numDisks = pegs[0].length;
    int diskSize = 0;

    // Find and remove the top disk from the source peg
    for (int i = numDisks - 1; i >= 0; i--) {
        if (pegs[fromPeg][i] != 0) {
            diskSize = pegs[fromPeg][i];
            pegs[fromPeg][i] = 0;
            break;
        }
    }

    // Place the disk on the target peg's first empty slot
    for (int i = numDisks - 1; i >= 0; i--) {
        if (pegs[toPeg][i] == 0) {
            pegs[toPeg][i] = diskSize;
            break;
        }
    }

    // Show the updated state after moving
    System.out.println("\nMoved disk " + diskSize + " from Peg " + (fromPeg + 1) + " to Peg " + (toPeg + 1));
    displayPegs(pegs);
}

3. Visualize the Tower State

Keep visualization separate from movement logic with a dedicated method:

public static void displayPegs(int[][] pegs) {
    int numDisks = pegs[0].length;
    // Print from top to bottom of the towers
    for (int i = numDisks - 1; i >= 0; i--) {
        for (int j = 0; j < 3; j++) {
            int disk = pegs[j][i];
            if (disk == 0) {
                System.out.print("|   | "); // Empty slot
            } else {
                // Print a proportional disk (wider for larger sizes)
                String diskStr = String.format("|%"+disk+"d%"+disk+"d|", disk, disk);
                System.out.print(diskStr + " ");
            }
        }
        System.out.println();
    }
    // Print peg labels for clarity
    System.out.println("-------------------------");
    System.out.println("  Peg 1   Peg 2   Peg 3  ");
}

4. Recursive Hanoi Solver

Keep the algorithm logic focused on the recursive steps, not array manipulation:

public static void solveHanoi(int numDisks, int fromPeg, int toPeg, int auxPeg, int[][] pegs) {
    if (numDisks == 1) {
        moveDisk(fromPeg, toPeg, pegs);
        return;
    }
    // Move n-1 disks from source to auxiliary
    solveHanoi(numDisks - 1, fromPeg, auxPeg, toPeg, pegs);
    // Move the largest disk from source to target
    moveDisk(fromPeg, toPeg, pegs);
    // Move n-1 disks from auxiliary to target
    solveHanoi(numDisks - 1, auxPeg, toPeg, fromPeg, pegs);
}

Step 3: Tie It All Together in Main

Update your main method to use these modular components:

import java.util.Scanner;

public class TowerOfHanoi {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter number of disks:");
        int numDisks = scan.nextInt();
        scan.close();

        // Initialize and show starting state
        int[][] pegs = initializePegs(numDisks);
        System.out.println("\nStarting State:");
        displayPegs(pegs);

        // Solve the puzzle (using 0-based peg indices internally)
        solveHanoi(numDisks, 0, 2, 1, pegs);

        System.out.println("\nPuzzle solved!");
    }

    // Paste all the modular methods here: initializePegs, moveDisk, displayPegs, solveHanoi
}

Why This Works for Modularity

  • Each method has a clear, single purpose: no mixing initialization with movement, or visualization with recursion.
  • You can tweak any part (e.g., change the visualization format, adjust disk numbering) without breaking the rest of the code.
  • The recursive algorithm stays focused on the Hanoi logic, not low-level array operations.

内容的提问来源于stack exchange,提问作者Skeletonized

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:21:28