如何找到渗滤路径并突出显示?

时间:2018-08-08 09:43:26

标签: javascript algorithm union

我使用快速联合算法来查找前5个站点之一是否与后5个站点之一连接。

前五个站点具有相同的根,这是倒数第二个数组元素。最后五个站点也具有相同的根。这是最后一个数组元素。

Aug 2018
Sep 2018
Oct 2018

我需要绘制一条这样的路径enter image description here

我用来突出显示网站的代码是:

for (let i = 0; i < 5; i++) {
        this.union(i,this.array.length-2);
    }
    for (let j = this.array.length-this.number-2; j < this.array.length-2; j++) {
        this.union(j,this.array.length-1);
    }

结果: enter image description here

但是突出显示左侧2个网站并不正确。 enter image description here 我应该使用哪种算法仅突出显示正确的路径?

连接方法:

let id =   this.array[this.array.length-2]
for (let i = 0; i < this.array.length-2; i++) {
    if(this.connected(i,id) && $("#result td").eq(i).hasClass('opened')){
        $("#result td").eq(i).css({'background':'blue'});
    }

}

根方法

connected(p, q){
    return this.root(p) === this.root(q);
}

1 个答案:

答案 0 :(得分:1)

看起来您只需要基本的Fill算法,但有两个警告。 1)您只希望它向下填充,就像水在流动一样。2)您想要在第一行(顶部)的每个空白处调用Fill(),就像在顶部浇水一样。

var EMPTY = 0; // empty unfilled spot
var SOLID = 1; // solid spot
var FILLED = 2; // filled spot
var ROWS = 5; // # of rows of data indexed 0 to 4
var COLS = 5; // # of columns of data indexed 0 to 4
var data = [
    [1,0,0,1,1],
    [1,1,0,1,1],
    [0,1,0,0,1],
    [0,1,1,0,1],
    [0,1,1,0,1]
]; // data that matches the example

// check if a location is EMPTY
function isEmpty(grid, rowIndex, colIndex) {
    // valid row and col?
    if(rowIndex < 0 || rowIndex >= ROWS || colIndex < 0 || colIndex >= COLS) {
        return false;
    }
    // SOLID or FILLED already?
    if(grid[rowIndex][colIndex] !== EMPTY) {
        return false;
    }
    return true;
}

// replace EMPTY locations with FILLED locations
function fillDown(grid, startRow, startCol) {
    if(false === isEmpty(grid, startRow, startCol)) {
        return;
    }
    var nextLocation = [[startRow, startCol]]; // list of locations to process
    while(nextLocation.length > 0) { // loop
        var loc = nextLocation.pop();
        var r = loc[0]; // row index
        var c = loc[1]; // column index
        // fill the empty location
        grid[r][c] = FILLED;
        // try to fill the locations to the LEFT, RIGHT and DOWN from the current location
        if(isEmpty(grid, r, c - 1)) { // left
            nextLocation.push([r, c - 1]);
        }
        if(isEmpty(grid, r, c + 1)) { // right
            nextLocation.push([r, c + 1]);
        }
        if(isEmpty(grid, r + 1, c)) { // down
            nextLocation.push([r + 1, c]);
        }
    }
}

// call fillDown() for the first row of the data (water pouring accross the top)
for(var c = 0; c < COLS; c++) {
    fillDown(data, 0, c);
}

// show the result
alert(data.join('\n'));

2d数组的额外注释,行和列索引可以通过以下公式转换为1d数组索引:index =(r * COLS)+ c,因此数据行中的最后一个位置= 4,col = 4将是4 * 5 + 4 == 24,即一维数组中最后一个位置的索引。

相关问题