0

I am going crazy with this problem! My solution is in Java - I have tried different inputs and haven't been able to reproduce the alleged wrong answer. Maybe someone here could possibly point to my solutions bottlenecks?

The verdict I am getting from UVa judge is "Wrong Answer".

// FOUND THE SOLUTION - I WAS PRINTING null chars at the end of some lines ('\u0000'). The problem is solved by adding if(maze[j][i] != '\u0000') before calling bufferedWriter.write(maze[j][i]

Thanks to everyone!

The intial code:

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

}
Reins
  • 1,109
  • 1
  • 17
  • 35
  • Is it possible for you to at least figure out which test case it failed on? A blanket "why is this code getting WA" question probably won't get much; we know even less than you right now. – Dennis Meng Feb 20 '14 at 22:35
  • UVa doesn't give any info about the wrong answer. My bet would be that it might be a formatting issue because I haven't been able to produce a wrong answer with the algorithm. – Reins Feb 21 '14 at 05:00
  • This would fit better on http://codereview.stackexchange.com/, if you want to have someone run through your code. – skiwi Feb 21 '14 at 10:47
  • Thanks, next time I'll know. :) – Reins Feb 24 '14 at 15:13
  • @skiwi I was under the impression that the Code Review guys usually will only review working code. Has that changed? (Plus, posting either here or on Code Review still shouldn't be a substitute for learning how to whittle down the problem. If you in an actual competition, we're not exactly a resource that'll be available) – Dennis Meng Feb 24 '14 at 16:30

1 Answers1

1

One very clear bug in your solution is that you are printing extra 'space characters' in your solution which is probably not what the question asked. For example, in the first sample output, you are printing extra spaces in the lower 5 lines. You can solve this problem by using an arraylist of array to store the input and then output that arraylist.

Also, you should probably output a new line after every line of output. (You are not doing so for the last line of output.)

Here is a link to my accepted solution for this problem.

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);
    }
}
Nikunj Banka
  • 11,117
  • 16
  • 74
  • 112
  • Could you please clarify where do I print extra white-space characters? Thanks in advance! – Reins Feb 24 '14 at 15:12
  • I found with debugger that I am writing '\u0000' chars on some occasions - not entirely sure if this could be the problem (as they're not visible). Once I can access the UVA site I'll find out and let you know. – Reins Feb 24 '14 at 15:20
  • On testing your code locally on my machine, I saw that extra space characters are printed for an array of chars that has not been initialized. And you have done this in your code. You have created a 2D array of chars and are printing the array. But ideone does not print space characters for an unitialized array of chars. So I think it will be better if don't print an unitialized array. – Nikunj Banka Feb 24 '14 at 16:35