java - 使用 BufferedReader 进行递归

标签 java arrays recursion arraylist bufferedreader

在我的计算机科学课上,我们遇到了一个我似乎无法解决的问题。问题如下。我们还必须使用洪水填充算法

Create a program that reads a text file containing a 15 x 15 grid, which represents human cells. The cells are depicted with a plus sign “+” if they are healthy cells, and a minus sign “-” if they are cancerous. The outside rows and columns of the grid will contain only plus signs “+”." Basically whats going to happen is you need to use recursion to check every item in the txt file and if the character is a "-" then you change it to " " and if the character is "+" you leave it as "+".

这是我目前拥有的代码。到目前为止,我已将文本文件放入数组列表中,然后创建了一个字符串数组。我不确定如何检查每个值以查看它们是否是“-”,因为一旦我能够做到这一点,递归应该相当简单。任何帮助将不胜感激!

public class Cancer {

  public static void main(String[] args) throws IOException {

      String[][] grid = new String[14][14];

      BufferedReader in = new BufferedReader(new FileReader("location.txt"));
      String str=null;
        ArrayList<String> lines = new ArrayList<String>();
        while((str = in.readLine()) != null){
            lines.add(str);
        }
        String[] linesArray = lines.toArray(new String[lines.size()]);
  }
}

最佳答案

首先,我认为您最好使用字符网格,但让我们继续使用字符串方法:

当您声明数组时,您也声明了其大小,因此具有 15 个元素的字符串数组将被声明为 new String[15]

我真的不明白为什么你需要一个二维字符串数组,因为一个字符串是一整行(行)。 这是程序的稍微修改版本,它将文件的行读入一维字符串数组,然后循环遍历每行中的每个字符并查找“癌症”(迭代):

import java.util.*;
import java.io.*;

public class Cancer {

  public static void main(String[] args) throws IOException {

      String[] grid = new String[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;
            i++;
        }

        for (int x = 0; x < grid.length; x++) {
            String row = grid[x];
            for (int y = 0; y < row.length(); y++) {
                if(row.charAt(y) == '-') {
                    System.out.println("Cancer found at " + x + "," + y);
                }
            }
        }
  }
}

希望这能让您了解如何检查您的输入。 String 和 charAt 方法没有任何问题(因为“网格”变成一维),它只是使实际的“算法”的可移植性稍差一些。正如其他人提到的,使用递归解决这个问题有点奇怪。一种方法是利用网格坐标进行递归调用。另一种选择是“砍掉”数组/字符串。

关于java - 使用 BufferedReader 进行递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23162153/

相关文章:

java - 无法从 Maven 运行 testNG 测试

java - (Java) 类里面的困难

php - 在 foreach 循环中使用 PHP 解析数组值

c - 使用递归函数以相反顺序打印数组

java - Intellij诊断崩溃问题

java - 如何一起使用 JUnit 和 Hamcrest?

PHP删除数组中的重复项

javascript - 如何将字符串添加到数组并返回字符串

javascript - 我无法理解 Y-Combinator,所以我尝试实现它并最终得到了一些更短的东西,但它起作用了。这怎么可能?

c - 使用递归的链表 - 意外的输出