java - UVa-784 错误答案

标签 java algorithm flood-fill

<分区>

我快要被这个弄疯了 problem ! 我的解决方案是用 Java 编写的——我尝试了不同的输入,但无法重现所谓的错误答案。也许这里有人可以指出我的解决方案瓶颈?

我从 UVa 法官那里得到的判决是“错误答案”。

//找到解决方案 - 我在某些行的末尾打印空字符 ('\u0000')。 通过在调用 bufferedWriter.write(maze[j][i]

谢谢大家!

初始代码:

import java.io.*;

class Main {
    public static final int MAX_NUMBER_OF_LINES = 31;
    public static final int MAX_NUMBER_OF_CHARACTERS_PER_LINE = 81;

    public static char[][] maze;
    public static boolean[][] visitedLocations;
    public static int numberOfMazes;
    public static int numberOfLines;
    public static int numberOfChars;

    public static BufferedReader bufferedReader;
    public static BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String args[]) throws IOException {
        readFromStandardInput();
        bufferedWriter.flush();
    }

    public static void readFromStandardInput() throws IOException {
        bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String line;
        numberOfMazes = Integer.parseInt(bufferedReader.readLine());
        int lineCounter = 0;
        while (numberOfMazes > 0) {
            maze = new char[MAX_NUMBER_OF_CHARACTERS_PER_LINE][MAX_NUMBER_OF_LINES];
            visitedLocations = new boolean[MAX_NUMBER_OF_CHARACTERS_PER_LINE][MAX_NUMBER_OF_LINES];
            lineCounter = 0;
            while ((line = bufferedReader.readLine()) != null) {
                if (line.charAt(0) == '_') {
                    break;
                } else {
                    constructArrayLineByLine(line, lineCounter);
                }
                lineCounter++;
            }
            numberOfLines = lineCounter;
            solvePreviousMaze();
            bufferedWriter.write(line);
            numberOfMazes--;
            if (numberOfMazes > 0) {
                bufferedWriter.write("\n");
            }
        }
    }

    public static void solvePreviousMaze() throws IOException {
        for (int i = 1; i < numberOfLines; i++) {
            for (int j = 1; j < numberOfChars; j++) {
                if (maze[j][i] == '*') {
                    floodTheMaze(i, j);
                    solutionToStandardOutput();
                    return;
                }
            }
        }
    }

    public static void solutionToStandardOutput() throws IOException {
        for (int i = 0; i < numberOfLines; i++) {
            for (int j = 0; j < numberOfChars; j++) {
                bufferedWriter.write(maze[j][i]);
            }
            bufferedWriter.write("\n");
        }
    }

    public static void floodTheMaze(int i, int j) {
        if (visitedLocations[j][i]) {
            return;
        } else {
            visitedLocations[j][i] = true;
        }
        if (maze[j][i] == ' ' || maze[j][i] == '*') {
            maze[j][i] = '#';
            floodTheMaze(i, j - 1);
            floodTheMaze(i - 1, j);
            floodTheMaze(i + 1, j);
            floodTheMaze(i, j + 1);
        }
    }

    public static void constructArrayLineByLine(String line, int numberOfLine) {
        numberOfChars = Math.max(numberOfChars, line.length());
        for (int i = 0; i < line.length(); i++) {
            maze[i][numberOfLine] = line.charAt(i);
        }
    }

}

最佳答案

您的解决方案中一个非常明显的错误是您在解决方案中打印了额外的“空格字符”,这可能不是问题所问的内容。例如,在第一个示例输出中,您在下面的 5 行中打印了额外的空格。您可以通过使用数组的数组列表来存储输入然后输出该数组列表来解决此问题。

此外,您可能应该在每行输出之后输出一个新行。 (你没有为最后一行输出这样做。)

Here是我接受的针对此问题的解决方案的链接。

import java.io.*;
import java.math.*;
import java.util.*;
import java.lang.*;

public class Main{ 

    public static InputStream inputStream = System.in;
    public static OutputStream outputStream = System.out;
    public static FastReader in = new FastReader(inputStream);
    public static PrintWriter out = new PrintWriter(outputStream);


    public static void main(String[] args)throws java.lang.Exception{
        new Main().run();
        out.close();
    }   

    int N;
    int M;
    boolean[][] dfsNode;
    StringTokenizer tk;
    char[][] grid;
    char[][] filled;
    String[] sep;

    void run()throws java.lang.Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine().trim());
        sep = new String[N];
        for(int i=0; i<N; i++){
            ArrayList<char[]> al = new ArrayList<char[]>();
            while(true){
                String s = br.readLine();
                if(s.contains("_")){
                    sep[i] = s;
                    break;
                }
                char[] arr = s.toCharArray();
                al.add(arr);
            }
            grid = new char[al.size()][];
            for(int j=0; j<al.size(); j++){
                grid[j] = al.get(j);
            }
            //           ArrayUtils.printGrid(grid);
            int stari = -1;
            int starj = -1;
            for(int j=0; j<grid.length; j++){
                for(int k=0; k<grid[j].length; k++){
                    if(grid[j][k] == '*'){
                        stari = j;
                        starj = k;
                        break;
                    }
                }
            }
            dfsNode = new boolean[grid.length][];
            filled = new char[grid.length][];
            for(int j=0; j<grid.length; j++){
                char[] arr = new char[grid[j].length];
                for(int k=0; k<grid[j].length; k++){
                    arr[k] = grid[j][k];
                }
                filled[j] = arr;
                dfsNode[j] = new boolean[grid[j].length];
            }
            fillColour(stari, starj);
            for(int j=0; j<filled.length; j++){
                for(int k=0; k<filled[j].length; k++){
                    if(filled[j][k] == '*'){
                        out.print(' ');
                    }else{
                        out.print(filled[j][k]);
                    }
                }
                out.println();
            }
            out.println(sep[i]);
        }
    }

    void fillColour(int row, int col){
        if(row<0 || row>=grid.length || col<0 || col>=grid[row].length){
            return;
        }
        if(dfsNode[row][col]){
            return;
        }

        // fill on border?
        if(grid[row][col]!=' ' && grid[row][col]!='*'){
            return;
        }

        filled[row][col] = '#';
        dfsNode[row][col] = true;
        fillColour(row-1, col);
        fillColour(row+1, col);
        fillColour(row, col-1);
        fillColour(row, col+1);
    }
}

class FastReader{
    private boolean finished = false;

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private SpaceCharFilter filter;

    public FastReader(InputStream stream){
        this.stream = stream;
    }

    public int read(){
        if (numChars == -1){
            throw new InputMismatchException ();
        }
        if (curChar >= numChars){
            curChar = 0;
            try{
                numChars = stream.read (buf);
            } catch (IOException e){
                throw new InputMismatchException ();
            }
            if (numChars <= 0){
                return -1;
            }
        }
        return buf[curChar++];
    }

    public int peek(){
        if (numChars == -1){
            return -1;
        }
        if (curChar >= numChars){
            curChar = 0;
            try{
                numChars = stream.read (buf);
            } catch (IOException e){
                return -1;
            }
            if (numChars <= 0){
                return -1;
            }
        }
        return buf[curChar];
    }

    public int nextInt(){
        int c = read ();
        while (isSpaceChar (c))
            c = read ();
        int sgn = 1;
        if (c == '-'){
            sgn = -1;
            c = read ();
        }
        int res = 0;
        do{
            if(c==','){
                c = read();
            }
            if (c < '0' || c > '9'){
                throw new InputMismatchException ();
            }
            res *= 10;
            res += c - '0';
            c = read ();
        } while (!isSpaceChar (c));
        return res * sgn;
    }

    public long nextLong(){
        int c = read ();
        while (isSpaceChar (c))
            c = read ();
        int sgn = 1;
        if (c == '-'){
            sgn = -1;
            c = read ();
        }
        long res = 0;
        do{
            if (c < '0' || c > '9'){
                throw new InputMismatchException ();
            }
            res *= 10;
            res += c - '0';
            c = read ();
        } while (!isSpaceChar (c));
        return res * sgn;
    }

    public String nextString(){
        int c = read ();
        while (isSpaceChar (c))
            c = read ();
        StringBuilder res = new StringBuilder ();
        do{
            res.appendCodePoint (c);
            c = read ();
        } while (!isSpaceChar (c));
        return res.toString ();
    }

    public boolean isSpaceChar(int c){
        if (filter != null){
            return filter.isSpaceChar (c);
        }
        return isWhitespace (c);
    }

    public static boolean isWhitespace(int c){
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    private String readLine0(){
        StringBuilder buf = new StringBuilder ();
        int c = read ();
        while (c != '\n' && c != -1){
            if (c != '\r'){
                buf.appendCodePoint (c);
            }
            c = read ();
        }
        return buf.toString ();
    }

    public String nextLine(){
        String s = readLine0 ();
        while (s.trim ().length () == 0)
            s = readLine0 ();
        return s;
    }

    public String nextLine(boolean ignoreEmptyLines){
        if (ignoreEmptyLines){
            return nextLine ();
        }else{
            return readLine0 ();
        }
    }

    public BigInteger nextBigInteger(){
        try{
            return new BigInteger (nextString ());
        } catch (NumberFormatException e){
            throw new InputMismatchException ();
        }
    }

    public char nextCharacter(){
        int c = read ();
        while (isSpaceChar (c))
            c = read ();
        return (char) c;
    }

    public double nextDouble(){
        int c = read ();
        while (isSpaceChar (c))
            c = read ();
        int sgn = 1;
        if (c == '-'){
            sgn = -1;
            c = read ();
        }
        double res = 0;
        while (!isSpaceChar (c) && c != '.'){
            if (c == 'e' || c == 'E'){
                return res * Math.pow (10, nextInt ());
            }
            if (c < '0' || c > '9'){
                throw new InputMismatchException ();
            }
            res *= 10;
            res += c - '0';
            c = read ();
        }
        if (c == '.'){
            c = read ();
            double m = 1;
            while (!isSpaceChar (c)){
                if (c == 'e' || c == 'E'){
                    return res * Math.pow (10, nextInt ());
                }
                if (c < '0' || c > '9'){
                    throw new InputMismatchException ();
                }
                m /= 10;
                res += (c - '0') * m;
                c = read ();
            }
        }
        return res * sgn;
    }

    public boolean isExhausted(){
        int value;
        while (isSpaceChar (value = peek ()) && value != -1)
            read ();
        return value == -1;
    }

    public String next(){
        return nextString ();
    }

    public SpaceCharFilter getFilter(){
        return filter;
    }

    public void setFilter(SpaceCharFilter filter){
        this.filter = filter;
    }

    public interface SpaceCharFilter{
        public boolean isSpaceChar(int ch);
    }
}

关于java - UVa-784 错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21919057/

相关文章:

javascript - 如何使用selenium RC获取页面源

java - 可以将 IntelliJ 配置为在不使用快捷方式的情况下调用 SmartType 代码完成吗?

c# - 有什么办法可以加快这个文件解析算法?

algorithm - 算法说明 - 可达性矩阵

Android - 使用 Flood-Fill 时 Canvas 黑色

java - 使用 floodfill 计算矩阵中的相邻零点

java - 尝试在 Android 中动态修改 ListView 的字体的空指针异常

java - double

algorithm - 特定意图的二叉搜索树

javascript - 如何使用 HTML Canvas 执行洪水填充?