Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

algorithm to find the largest area

................................
.XXXXXXXXXXXXXXX.....XXXXXXXXXX.
.X.....X.......X.....X........X.
.X.....X.......XXXXXXX........X.
.XXXXXXXXXXXX.................X.
.X....X.....X.................X.
.X....X.....XXXX..............X.
.XXXXXX........X..............X.
......X........X..............X.
......X........X..............X.
......X........X..............X.
......XXXXXXXXXXXXXXXXXXXXXXXXX.
................................

Looking for an algorithm to find the largest area. Here, "area" is defined as a number of dots (.) bounded by Xs.

   private static void readFile(File inputFile) throws IOException {

    Scanner fileScanner = new Scanner(inputFile);

    Point previousPoint = null;

    int rowCount = 0;
    while(fileScanner.hasNext()){
        String line = fileScanner.next();

        String[] points = line.split(" ");

        for(int columnCount=0;columnCount<points.length;columnCount++){

            if(points[columnCount].equalsIgnoreCase("x")){
                Point currentPoint = new Point();
                currentPoint.setxValue(columnCount);
                currentPoint.setyValue(rowCount);
            }
        }

        rowCount++;
    }
  }

This is my first and struggling to move further.

like image 807
user1578872 Avatar asked Oct 16 '13 17:10

user1578872


1 Answers

This algorithm should work. You just need to implement it in Java.

  1. Load the file into a char[][]. (1 char[] per line)
  2. Loop through the char[][] (2 dimensionally)
    1. upon finding a '.', perform flood fill, changing all '.' to ',', also incrementing a counter on every change.
    2. At the end of flood fill, compare this counter with a globally set maximum. If it's higher, then set it as the new highest. (If the edges are not a proper boundary, then do not set this counter if you reached an edge during flood fill by setting a flag during 3)
  3. Return the highest you set.

If you have any specific problems with the Java implementation, then let me know

Geobits:

Note: If you want to exclude the area "outside" any boxes, flood as usual, but discard any area that hits the edge during the fill(skip step 2.2 for that flood).

When doing the flood fill, you have 2 types of boundaries. A wall ('X'), and the edge of the array(which you need to explicitly check for to avoid OutOfBounds exceptions). If you hit an out of bounds, keep doing the fill, but set a flag so you know later to not consider the number you counted for the biggest box.

like image 101
Cruncher Avatar answered Oct 06 '22 16:10

Cruncher