对于我的一个课程,我有一个问题,我必须采取所有的"癌症"文本文件的单元格,并使用泛洪填充算法去除它们。
这是一个确切的问题:
创建一个程序,读取包含15 x 15网格的文本文件,该网格代表人体细胞。如果细胞是健康细胞,则用加号“+”描绘细胞,如果它们是癌细胞则用“ - ”加号。网格的外部行和列将仅包含加号“+”。注意:使用Flood Fill算法确定此信息。
到目前为止,我可以将至少一个癌细胞区域改为" "
,但我无法获得另一个。这就是我到目前为止所拥有的。这是它应该是什么样子的一个例子:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class floodIntro {
// Make global variables (grid&blobSize) which are accessible
// from anywhere inside the class FloodIntro
public static Character newGrid[][];
public static int blobSize;
public static void main(String[] args) throws IOException{
String[] grid = new String[15];
newGrid = new Character[15][15];
BufferedReader in = new BufferedReader(new FileReader("location.txt"));
String str = null;
ArrayList<String> lines = new ArrayList<String>();
int i = 0;
while ((str = in.readLine()) != null) {
grid[i] = str;
// System.out.println(str);
i++;
}
// so far can print out every line listed above
for (int x = 0; x < grid.length; x++) {
// for every line in the grid
for (int y = 0; y < grid[x].length(); y++) {
newGrid[x][y] = grid[x].charAt(y);
}
}
// Print out the current grid
displayGrid();
// variable to determine the size of the blob
blobSize = 0;
// Pick one random element in the array that is not along the
// border and remove the blob at that location
// NOTE: if a blank is chosen, the blob size is 0
// and nothing is removed
int blobRow = (int) (Math.random() * 13 + 1);
int blobCol = (int) (Math.random() * 13 + 1);
System.out.println("The blob at " + blobRow + "," + blobCol + " will be removed.");
floodFill(blobRow, blobCol);
System.out.println("The blob had " + blobSize + " items in it");
System.out.println("The new grid is:");
// Print out the new grid
displayGrid();
}
public static void floodFill(int row, int col) {
if (newGrid[row][col].equals('-')) {
newGrid[row][col] = ' ';
blobSize++;
floodFill(row - 1, col - 1);
floodFill(row - 1, col);
floodFill(row - 1, col + 1);
floodFill(row, col - 1);
floodFill(row, col + 1);
floodFill(row + 1, col - 1);
floodFill(row + 1, col);
floodFill(row + 1, col + 1);
}
}
public static void displayGrid() {
String output="";
for (int row = 0; row <= 14; row++) {
for (int col = 0; col <= 14; col++) {
output += newGrid[row][col];
}
output += "\n";
}
System.out.println(output);
}
}
以下是正在使用的txt文件:
+++++++++++++++
++--+++++++++++
++---++++++++++
+----++++++++++
++++-++++++++++
+++++++++++++++
+++++++++++++++
+++++++++-----+
+++++++-----+++
+++++-----+++++
++++++------+++
+++++++-----+++
+++++++++--++++
++++++++++-++++
+++++++++++++++
答案 0 :(得分:1)
一个问题是随机生成位置:
int blobRow = (int) (Math.random() * 13 + 1);
int blobCol = (int) (Math.random() * 13 + 1);
可能不会以-
结束,因此无法执行任何操作(如果您获得+
,则不会进入if语句。)
您可以在this demo中看到,如果您传递有效坐标,它确实可以正确填充癌症斑点。
除此之外,你应该实际进行洪水填充几次(每个癌症点一次)。类似的东西:
-
(通过循环整个网格)