根据2D网格阵列上的单元格值查找路径

时间:2017-05-16 23:41:48

标签: java algorithm swing 2d path-finding

我有一个由JLabel组成的网格。每个单元格有3种状态:     public enum Token {     VIDE,CERCLE_ROUGE,CERCLE_BLEU     } 空单元格== Token.VIDE

我有这个简单的算法找到给定单元格的所有邻居然后我使用swing自定义绘画在标签中心作为点的路径之后绘制多边形。

private CellsList getNeighbors(int  row, int col) {
    CellsList neighbors = new CellsList();
    for (int colNum = col - 1 ; colNum <= (col + 1) ; colNum +=1  ) {
        for (int rowNum = row - 1 ; rowNum <= (row + 1) ; rowNum +=1  ) {
            if(!((colNum == col) && (rowNum == row))) {
                if(withinGrid (rowNum, colNum )  ) {
                    neighbors.add( new int[] {rowNum, colNum});
                }
            }
        }
    }

    return neighbors;
}

这是获得路径的条件:

if((size() >= MIN_PATH_LEGTH) && neighbors.contains(origin)  ) {
            add(cell);
            return true;
        }

现在我想通过添加条件来使其更加精确,如果只有至少4个单元格在邻域中找到相同的值并且至少有一个相反的值,则路径可以是有效的。

实施例: (11,10)(10,11)(11,12)(12,11)处的红细胞可以形成有效路径,只要处至少有一个蓝色细胞(11) ,11)。 (见下图)

enter image description here

以下不能是有效路径,因此没有绘图:

enter image description here

现在,算法找到的路径只有我定义的最小值(int MIN_PATH_LEGTH = 3),但我找不到定义第二个条件的方法(至少一个相反的单元格值在附近

如果需要,我会使用新元素进行编辑。

3 个答案:

答案 0 :(得分:2)

如果redCell的路径OK,则在调用此方法之前进行

测试:

public boolean isThereABlueCellWithinMyRedPath() {
    // height = height of your map
    // width = width of yout map
    // this array is suppose to be in an other place...
    Cell[][] cellArray = new Cell[height][width];
    // ... so are those two lists
    List<Cell> blueCellsList = new ArrayList<>();
    List<Cell> redCellsList = new ArrayList<>();

    //foreach blueCell on the map ...
    for (Cell blueCell : blueCellsList) {
        boolean north = false;
        boolean east = false;
        boolean south = false;
        boolean west = false;
        int originX = blueCell.getX();
        int originY = blueCell.getY();

        // ... if there is a redCell at north...
        for (int i = originY; i >= 0; i--) {
            if (redCellsList.contains(cellArray[originX][i])) {
                north = true;
                break;
            }
        }
        // ... East ...
        for (int i = originX; i < cellArray[originX].length; i++) {
            if (redCellsList.contains(cellArray[i][originY])) {
                east = true;
                break;
            }
        }
        // ... South ...
        for (int i = originY; i < cellArray.length; i++) {
            if (redCellsList.contains(cellArray[originX][i])) {
                south = true;
                break;
            }
        }
        // ... West ...
        for (int i = originX; i >= 0; i--) {
            if (redCellsList.contains(cellArray[i][originY])) {
                west = true;
                break;
            }
        }
        // ... I am surrended by redCell
        if (south && east && north && west)
            return true;
    }
    return false;
}

我没有尝试代码,但它似乎有效。

答案 1 :(得分:1)

也许你可以列出蓝色细胞和红细胞,如果你想测试红细胞路径中是否有蓝色细胞,你可以:

转到NORTH直到你遇到redCell或地图限制:如果是地图限制你用下一个blueCell测试,否则你回到你的位置并对EAST,SOUTH,WEST做同样的事情。 如果在4方面你首先找到redCell,你返回true,否则你返回false。

如果你想在一个非常小的地图上进行测试就足够了。但如果红细胞形成的形状可以自由,我找不到更好的方法。

答案 2 :(得分:1)

我的回答是基于previous answer中发布的代码。

路径类
添加isWithinLoop以检查单元格是否在路径中,方法是检查它是否有 路径单元格左侧,右侧,顶部和底部。
还添加getContainedWithin,它返回由路径限定的所有单元格的集合,并且它们的标记与路径的颜色相反

    //returns a collection of all cells that are bounded by the path 
    //and their token is of the opposite color of the path 
    List<int[]> getContainedWithin() {

        //find path max and min X values, max and min Y values
        minPathRow = grid[0].length; //set min to the largest possible value
        maxPathCol = grid.length;
        maxPathRow = 0;              //set max to the largest possible value
        maxPathCol = 0;

        //find the actual min max x y values of the path
        for (int[] cell : this) {
            minPathRow = Math.min(minPathRow, cell[0]);
            minPathCol = Math.min(minPathCol, cell[1]);
            maxPathRow = Math.max(maxPathRow, cell[0]);
            maxPathCol = Math.max(maxPathCol, cell[1]);
        }

        //todo remove after testing
        System.out.println("x range: "+minPathRow + "-" 
        + maxPathRow + " y range: " + minPathCol + "-" + maxPathCol);

        List<int[]> block = new ArrayList<>(25);
        int[] cell = get(0);//get an arbitrary cell in the path
        Token pathToken = grid[cell[0]][cell[1]]; //keep a reference to its token

        //iterate over all cells within path x, y limits
        for (int col = minPathCol; col < (maxPathCol); col++) {

            for (int row = minPathRow; row < (maxPathRow); row++) {

                //check cell color
                Token token = grid[row][col];
                if ((token == pathToken) || (token == Token.VIDE)) {
                    continue;
                }
                if (isWithinLoop(row,col)) {
                    block.add(new int[] {row, col});
                }
            }
        }

        return block;
    }

    //check if row, col represent a cell with in path by checking if it has a 
    //path-cell to its left, right, top and bottom 
    private boolean isWithinLoop(int row, int col) {

        if(  isPathCellOnLeft(row, col)
             &&
             isPathCellOnRight(row, col)
             &&
             isPathCellOnTop(row, col)
             &&
             isPathCellOnBottom(row, col)
          ) {
            return true;
        }

        return false;
    }

    private boolean isPathCellOnLeft(int cellRow, int cellCol) {

        for ( int col = minPathCol; col < cellCol ; col++) {

            if(getPath().contains(new int[] {cellRow, col})) {
                return true;
            }
        }

        return false;
    }

    private boolean isPathCellOnRight(int cellRow, int cellCol) {

        for ( int col = cellCol; col <= maxPathCol ; col++) {

            if(getPath().contains(new int[] {cellRow, col})) {
                return true;
            }
        }

        return false;
    }

    private boolean isPathCellOnTop(int cellRow, int cellCol) {

        for ( int row =minPathRow; row < cellRow ; row++) {

            if(getPath().contains(new int[] {row, cellCol})) {
                return true;
            }
        }

        return false;
    }

    private boolean isPathCellOnBottom(int cellRow, int cellCol) {

        for ( int row = cellRow; row <= maxPathRow; row++) {

            if(getPath().contains(new int[] {row, cellCol})) {
                return true;
            }
        }

        return false;
    }
}

模型类
添加访问getContainedWithin的getter方法:

List<int[]> getContainedWithin() {

    return (path == null ) ? null : path.getContainedWithin();
} 

控制类
如果ModelListener为空,请更新getContainedWithin以忽略路径:

private class ModelListener implements PropertyChangeListener {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            IndexedPropertyChangeEvent iEvt = (IndexedPropertyChangeEvent)evt;
            int index = iEvt.getIndex();
            int row = index / Model.COLS;
            int col = index % Model.COLS;
            Token token = (Token) evt.getNewValue();

            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {

                    view.setCell(token, row, col);
                    CellsList path = model.getPath();
                    //ignore path if null, empty or encloses no cell
                    if((path == null) || path.isEmpty()
                                        || model.getContainedWithin().isEmpty()) {
                        return;
                    }
                    view.addPath(path);
                    view.refresh();
                }
            });
        }
    }

可以为此repo下载完整的代码。