返回介绍

lcci / 08.06.Hanota / README_EN

发布于 2024-06-17 01:04:43 字数 7960 浏览 0 评论 0 收藏 0

08.06. Hanota

中文文档

Description

In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one). You have the following constraints:

(1) Only one disk can be moved at a time.
(2) A disk is slid off the top of one tower onto another tower.
(3) A disk cannot be placed on top of a smaller disk.

Write a program to move the disks from the first tower to the last using stacks.

Example1:


 Input: A = [2, 1, 0], B = [], C = []

 Output: C = [2, 1, 0]

Example2:


 Input: A = [1, 0], B = [], C = []

 Output: C = [1, 0]

Note:

  1. A.length <= 14

Solutions

Solution 1: Recursion

We design a function $dfs(n, a, b, c)$, which represents moving $n$ disks from $a$ to $c$, with $b$ as the auxiliary rod.

First, we move $n - 1$ disks from $a$ to $b$, then move the $n$-th disk from $a$ to $c$, and finally move $n - 1$ disks from $b$ to $c$.

The time complexity is $O(2^n)$, and the space complexity is $O(n)$. Here, $n$ is the number of disks.

class Solution:
  def hanota(self, A: List[int], B: List[int], C: List[int]) -> None:
    def dfs(n, a, b, c):
      if n == 1:
        c.append(a.pop())
        return
      dfs(n - 1, a, c, b)
      c.append(a.pop())
      dfs(n - 1, b, a, c)

    dfs(len(A), A, B, C)
class Solution {
  public void hanota(List<Integer> A, List<Integer> B, List<Integer> C) {
    dfs(A.size(), A, B, C);
  }

  private void dfs(int n, List<Integer> a, List<Integer> b, List<Integer> c) {
    if (n == 1) {
      c.add(a.remove(a.size() - 1));
      return;
    }
    dfs(n - 1, a, c, b);
    c.add(a.remove(a.size() - 1));
    dfs(n - 1, b, a, c);
  }
}
class Solution {
public:
  void hanota(vector<int>& A, vector<int>& B, vector<int>& C) {
    function<void(int, vector<int>&, vector<int>&, vector<int>&)> dfs = [&](int n, vector<int>& a, vector<int>& b, vector<int>& c) {
      if (n == 1) {
        c.push_back(a.back());
        a.pop_back();
        return;
      }
      dfs(n - 1, a, c, b);
      c.push_back(a.back());
      a.pop_back();
      dfs(n - 1, b, a, c);
    };
    dfs(A.size(), A, B, C);
  }
};
func hanota(A []int, B []int, C []int) []int {
  var dfs func(n int, a, b, c *[]int)
  dfs = func(n int, a, b, c *[]int) {
    if n == 1 {
      *c = append(*c, (*a)[len(*a)-1])
      *a = (*a)[:len(*a)-1]
      return
    }
    dfs(n-1, a, c, b)
    *c = append(*c, (*a)[len(*a)-1])
    *a = (*a)[:len(*a)-1]
    dfs(n-1, b, a, c)
  }
  dfs(len(A), &A, &B, &C)
  return C
}
/**
 Do not return anything, modify C in-place instead.
 */
function hanota(A: number[], B: number[], C: number[]): void {
  const dfs = (n: number, a: number[], b: number[], c: number[]) => {
    if (n === 1) {
      c.push(a.pop()!);
      return;
    }
    dfs(n - 1, a, c, b);
    c.push(a.pop()!);
    dfs(n - 1, b, a, c);
  };
  dfs(A.length, A, B, C);
}

Solution 2: Iteration (Stack)

We can use a stack to simulate the recursive process.

We define a struct $Task$, which represents a task, where $n$ represents the number of disks, and $a$, $b$, $c$ represent the three rods.

We push the initial task $Task(len(A), A, B, C)$ into the stack, and then continuously process the task at the top of the stack until the stack is empty.

If $n = 1$, then we directly move the disk from $a$ to $c$.

Otherwise, we push three subtasks into the stack, which are:

  1. Move $n - 1$ disks from $b$ to $c$ with the help of $a$;
  2. Move the $n$-th disk from $a$ to $c$;
  3. Move $n - 1$ disks from $a$ to $b$ with the help of $c$.

The time complexity is $O(2^n)$, and the space complexity is $O(n)$. Here, $n$ is the number of disks.

class Solution:
  def hanota(self, A: List[int], B: List[int], C: List[int]) -> None:
    stk = [(len(A), A, B, C)]
    while stk:
      n, a, b, c = stk.pop()
      if n == 1:
        c.append(a.pop())
      else:
        stk.append((n - 1, b, a, c))
        stk.append((1, a, b, c))
        stk.append((n - 1, a, c, b))
class Solution {
  public void hanota(List<Integer> A, List<Integer> B, List<Integer> C) {
    Deque<Task> stk = new ArrayDeque<>();
    stk.push(new Task(A.size(), A, B, C));
    while (stk.size() > 0) {
      Task task = stk.pop();
      int n = task.n;
      List<Integer> a = task.a;
      List<Integer> b = task.b;
      List<Integer> c = task.c;
      if (n == 1) {
        c.add(a.remove(a.size() - 1));
      } else {
        stk.push(new Task(n - 1, b, a, c));
        stk.push(new Task(1, a, b, c));
        stk.push(new Task(n - 1, a, c, b));
      }
    }
  }
}

class Task {
  int n;
  List<Integer> a;
  List<Integer> b;
  List<Integer> c;

  public Task(int n, List<Integer> a, List<Integer> b, List<Integer> c) {
    this.n = n;
    this.a = a;
    this.b = b;
    this.c = c;
  }
}
struct Task {
  int n;
  vector<int>* a;
  vector<int>* b;
  vector<int>* c;
};

class Solution {
public:
  void hanota(vector<int>& A, vector<int>& B, vector<int>& C) {
    stack<Task> stk;
    stk.push({(int) A.size(), &A, &B, &C});
    while (!stk.empty()) {
      Task task = stk.top();
      stk.pop();
      if (task.n == 1) {
        task.c->push_back(task.a->back());
        task.a->pop_back();
      } else {
        stk.push({task.n - 1, task.b, task.a, task.c});
        stk.push({1, task.a, task.b, task.c});
        stk.push({task.n - 1, task.a, task.c, task.b});
      }
    }
  }
};
func hanota(A []int, B []int, C []int) []int {
  stk := []Task{{len(A), &A, &B, &C}}
  for len(stk) > 0 {
    task := stk[len(stk)-1]
    stk = stk[:len(stk)-1]
    if task.n == 1 {
      *task.c = append(*task.c, (*task.a)[len(*task.a)-1])
      *task.a = (*task.a)[:len(*task.a)-1]
    } else {
      stk = append(stk, Task{task.n - 1, task.b, task.a, task.c})
      stk = append(stk, Task{1, task.a, task.b, task.c})
      stk = append(stk, Task{task.n - 1, task.a, task.c, task.b})
    }
  }
  return C
}

type Task struct {
  n     int
  a, b, c *[]int
}
/**
 Do not return anything, modify C in-place instead.
 */
function hanota(A: number[], B: number[], C: number[]): void {
  const stk: any[] = [[A.length, A, B, C]];
  while (stk.length) {
    const [n, a, b, c] = stk.pop()!;
    if (n === 1) {
      c.push(a.pop());
    } else {
      stk.push([n - 1, b, a, c]);
      stk.push([1, a, b, c]);
      stk.push([n - 1, a, c, b]);
    }
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文