[英]Creating Array of Integers to store spaces in grid Java
我目前正在制作一個程序,優化網格上房屋的放置以獲得最大利潤。
區域平面圖在網格上——所有房屋細節(尺寸等)都由用戶輸入。
所有房屋都必須放置在道路旁邊 - 道路已經由用戶添加到網格中。
我目前正在努力編寫一個 function 來檢查網格是否有任何可用空間來添加另一個房子(我的優化算法的停止條件)。
可用空間不是網格上的空方格,而是與道路相鄰的空方格。 (此路可橫豎均可go)
網格:
Coords[][] grid;
如果網格上的坐標是道路:
grid[x][y].getRoad() == true
以下 function 查找任意坐標的所有相鄰方格: (cols - 網格中的列數) (rows - 網格中的行數)
public static Coords[] addNeighboursSquare(Coords coord, int x, int y, int cols, int rows)
{
Coords[] neighbours = null;
//right
if (x < cols - 1)
{
neighbours[0] = AStarAlgorithm.grid[x + 1][y];
}
//left
if (x > 0)
{
neighbours[1] = AStarAlgorithm.grid[x - 1][y];
}
//top
if (y < rows - 1)
{
neighbours[2] = AStarAlgorithm.grid[x][y + 1];
}
//bottom
if (y > 0)
{
neighbours[3] = AStarAlgorithm.grid[x][y - 1];
}
return neighbours;
}
如何遍歷網格中的所有道路方塊,並創建一個包含道路上所有“間隙”大小的整數數組?
假設您的 function addNeighboursSquare()
將返回具有鄰居坐標的數組(您必須初始化數組鄰居),並且您可以檢查單元格是否為空(那里還沒有房子)我將從 function 開始,它返回我的間隙數細胞:
(偽代碼):
getGapsNumber(x, y):
gapsNumber := 0
neighbours := addNeighboursSquare(x,y)
for neighbour in neighbours:
if neighbour is empty
gapsNumber++
return gapsNumber
然后只需遍歷道路坐標並為它們調用getGapsNumber()
,例如:
(偽代碼):
totalGapsNumber := 0
for cell in road:
totalGapsNumber += getGapsNumber(cell.x, cell.y)
return getGapsNumber
如果您在一個地方沒有道路坐標,請遍歷整個網格並添加 if 語句,您可以在其中檢查單元格是否是道路。
(偽代碼):
totalGapsNumber := 0
for cell in grid:
if cell is road:
totalGapsNumber += getGapsNumber(cell.x, cell.y)
return getGapsNumber
這個怎么樣:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.