Posts

Showing posts from July, 2019

Finding the length of connected cells of 1's (regions) in an matrix of 1's and 0's

import java.io.*; class GFG {  static int max = 0;  static int count = 0;  public static void traverse(int a[][], int r, int c, int i, int j) {   if (i >= r || j >= c || i < 0 || j < 0) {    return;   }   if (a[i][j] == 0) {    return;   } else {    a[i][j] = 0;    count++;    traverse(a, r, c, i - 1, j);    traverse(a, r, c, i, j - 1);    traverse(a, r, c, i + 1, j);    traverse(a, r, c, i, j + 1);    traverse(a, r, c, i - 1, j - 1);    traverse(a, r, c, i + 1, j + 1);    traverse(a, r, c, i - 1, j + 1);    traverse(a, r, c, i + 1, j - 1);   }  }  public static void main(String[] args) {   int R = 5;   int C = 5;  int a[][] = { { 0, 0, 0, 0, 0}, { 0, 1, 1, 0, 0}, { 0, 0, 1, 0, 1}, { 1, 0, 0, 0, 1}, { 0, 1, 0, 1, 1} };   for (int i = 0; i < R; i++) {    for (int j = 0; j < C; j++) {     if (a[i][j] == 1) {      count = 0;      traverse(a, R, C, i, j);      if (count > max) {       max = count;