UVa-784错误的答案

时间:2014-02-20 20:39:25

标签: java algorithm flood-fill

我对这个problem感到很疯狂! 我的解决方案是Java - 我尝试了不同的输入,但无法重现所谓的错误答案。也许这里有人可能指出我的解决方案瓶颈?

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

//找到解决方案 - 我在某些行('\ u0000')的末尾打印了空字符。 在调用if(maze[j][i] != '\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);
        }
    }

}

1 个答案:

答案 0 :(得分:1)

您解决方案中的一个非常明显的错误是您在解决方案中打印了额外的“空格字符”,这可能与问题无关。例如,在第一个示例输出中,您将在较低的5行中打印额外的空格。您可以通过使用数组的arraylist来存储输入然后输出该arraylist来解决此问题。

此外,您应该在每行输出后输出一个新行。 (对于最后一行输出,您没有这样做。)

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);
    }
}