(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(