【问题标题】:finding path from tof left to bottom right in 2d array of 1's and 0's在 1 和 0 的二维数组中查找从左到右下的路径
【发布时间】:2015-12-02 23:35:25
【问题描述】:

我有 1 和 0 的二维数组。其中左上角和右下角用 1 填充,其余索引用 0 和 1 填充。

a[][]= {{1,1,0,0,1}{0,1,1,0,0}{0,1,0,1,0}{0,1,1,1,1}}.

编写一个程序/算法,它将返回另一个相同大小的二维数组,包含从开始到结束的路径。

output[][]={{1,1,0,0,0}{0,1,0,0,0}{0,1,0,0,0}{0,1,1,1,1}}

请帮我解决上述问题。该程序还应该适用于其他输入序列。

【问题讨论】:

  • 你尝试了什么?你被困在哪里了?
  • 今天的另一个作业:)
  • @vish4071 Homework questions are not a problem here。另一方面,缺乏研究工作是......
  • 是的,确切地说,顺便说一句...@Santosh,使用 bfs。
  • 您能发布您的解决方案吗?可能里面有小bug。

标签: java algorithm data-structures


【解决方案1】:

也许我可以为您提供更简洁的回溯算法版本。她你去:

import java.util.Arrays;

public class Backtrack {

    public static void main(String... args) {
        int[][] inputArray = {
                { 1, 1, 1, 0, 0 },
                { 0, 1, 1, 0, 0 },
                { 0, 1, 0, 1, 0 },
                { 0, 1, 1, 1, 1 } };
        int[][] findPath = findPath(inputArray);
        System.out.println(Arrays.deepToString(findPath));

    }

    public static int[][] findPath(int[][] maze) {
        int[][] solution = new int[maze.length][];
        for (int i = 0; i < maze.length; i++) {
            solution[i] = new int[maze[i].length];
        }
        if (!findPath(maze, solution, 0, 0)) {
            System.out.println("Didn't find a solution.");
        }
        return solution;
    }

    private static boolean findPath(int[][] maze, int[][] solution, int x, int y) {
        if (0 <= y && y < maze.length && 0 <= x && x < maze[y].length) {
            if (y == maze.length - 1 && x == maze[y].length - 1) {
                solution[y][x] = 1;
                return true;
            } else if (solution[y][x] != 1 && maze[y][x] == 1) {
                solution[y][x] = 1;
                if (findPath(maze, solution, x, y + 1)
                        || findPath(maze, solution, x + 1, y)
                        || findPath(maze, solution, x - 1, y)
                        || findPath(maze, solution, x, y - 1)) {
                    return true;
                }
                solution[y][x] = 0;
            }
        }
        return false;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-25
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 2018-06-17
    • 2015-05-09
    相关资源
    最近更新 更多