(UVA) Counting Cells in a Blob - Solution

I used Depth-First Search to solve this problem.


import java.io.*;

class Main {
    public static int[][] matrix;
    public static boolean[][] visited;
    public static int[] vx = {-1,-1,-1,0,0,1,1,1};
    public static int[] vy = {-1,0,1,-1,1,-1,0,1};
    public static int row;
    public static int col;
    public static int count;
   
    public static void dfs(int currX, int currY) {
        if (currX < 0 || currY < 0 || currX >= row || currY >= col || matrix[currX][currY] == 0 || visited[currX][currY] == true) {
            return;
        }
       
        visited[currX][currY] = true;
        count++;
        for (int i = 0; i < 8; i++) {
            int nextX = currX+vx[i];
            int nextY = currY+vy[i];
            dfs(nextX, nextY);
        }
    }
   
    public static void process() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       
        String line = br.readLine();
        int numCases = Integer.parseInt(line);
        line = br.readLine();
        for (int i = 0; i < numCases; i++) {
            if (i > 0) {
                System.out.println();
            }
           
            row = 0;
            col = 0;
            line = br.readLine();
            matrix = new int[25][25];
            visited = new boolean[25][25];
            while (!line.equals("")) {
                for (int j = 0; j < line.length(); j++) {
                    matrix[row][j] = line.charAt(j)-'0';
                }
               
                row++;
                col = line.length();
                line = br.readLine();
                if (line == null) {
                    break;
                }
            }
           
            int max = -1;
            for (int j = 0; j < row; j++) {
                for (int k = 0; k < col; k++) {
                    count = 0;
                    dfs(j, k);
                    if (count > max) {
                        max = count;
                    }
                }           
            }
           
            System.out.println(max);
        }
                               
        return;
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
       
        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução