首页 > 解决方案 > 在 JavaScript 中动画递归回溯算法

问题描述

我一直在尝试在递归函数中为回溯算法中的颜色变化设置动画。截至目前,当我运行该函数时,它仅在函数结束时更新颜色。

我在网上阅读了几篇文章,我认为这个问题的发生是因为它是同步运行的,而我需要异步运行它。

我在函数内部尝试了 setTimeout,但是它只会导致浏览器等待设定的时间,然后同时更新所有内容。

我现在将皇后区设置在有效位置,然后当我发现这些位置不再有效时,我使用 myFunction 将它们改回原来的颜色。

我对javascript有点陌生,所以任何见解都会有所帮助,谢谢。

  function myFunction(name, color) {
        document.getElementById(name).style.background = color;
    }

    function NQueen(col) {
        if (col == n) {
            return true;
        }
        // Checks if given move is valid for all positions in the column
        for (var i = 0; i < n; i++) {
            let square = "square" + i + col;
            if (isValid(i,col)) {
                board[i][col] = 1;
                let originalColor = document.getElementById(square).style.background;
                //setTimeout(function() {myFunction(square, color)}, 2000);
                myFunction(square, "rgb(255,0,0)");

                if (NQueen(col+1)) {    
                    return true;
                }

                myFunction(square, originalColor);  
                board[i][col] = 0;

            }

        }
        return false;
    }

编辑

我想我想出了一个解决方法,我制作了具有正方形名称和颜色的对象,并将它们放入数组中。然后我创建了一个递归函数来更改背景并使用 setTimeout 更新它。这有点奇怪,但它有效

    function myFunction(num) {
        var name = arr[num].square;
        var color = arr[num].color;
        document.getElementById(name).style.background = color;
        if (num < arr.length) setTimeout(function(){myFunction(num+1)}, 1000);

    }

标签: javascripthtml

解决方案


推荐阅读