lundi 28 décembre 2015

Efficient way to find whether a coordinate is a vertex/border coordinate?

Imagine a Cartesian plane and every Cell object represents a point in the plane (the plane will be the maze). When building my maze, I want to figure out whether a Cell object is a vertex (the four corner points) or just a border point (any cell that is on the edge of the maze, vertex points are also border points).

I need to know so that I can add neighboring cells as neighbors of the particular cell (I am creating a graph structure with nodes). Different borders have different requirements for what cells are neighbors (a top-right vertex for example cannot have a neighbor that is y + 1 or x + 1 as it is outside of the maze, whereas a bottom-left vertex cannot have y - 1 or x - 1).

How I tried to implement this was through a slew of if statements which I feel isn't a really good practice. So I wanted to ask whether there is a better way to know what type of coordinate a point is?

Here is how I did it:

private String typeOfBorderCell(Cell cell){
    if (!isBorderCell(cell)){
        throw new IllegalArgumentException("cell is not a border cell");
    }
    double x = cell.getCoordinate().getX();
    double y = cell.getCoordinate().getY();

    // Vertices
    if (x == 0 && y == 0){
        return "bottom-left";
    }

    else if (x == 0 && y == height - 1){
        return "top-left";
    }

    else if (x == width - 1 && y == 0){
        return "bottom-right";
    }

    else if (x == width - 1 && y == height - 1){
        return "top-right";
    }

    // Non-Vertices
    else if (x == 0 && (y > 0 && y < height - 1)){
        return "left";
    }

    // and so on for the other three non-vertex borders
}

The height/width are the size of the maze, but I had to subtract 1 as the maze coordinates start at origin (0,0) thus a 5x5 maze goes up to a max of 4 for its y and 4 for its x.

Doing this, I would get a total of 8 conditional statements (and the method that uses this method would require a switch statement with 8 cases as well). Is there a more efficient way to do this without a bunch of conditional statements?

Aucun commentaire:

Enregistrer un commentaire