Skip to content

Instantly share code, notes, and snippets.

@ldong
Last active November 8, 2017 03:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ldong/0e8ce24c61de23f534688979c79da45b to your computer and use it in GitHub Desktop.
Save ldong/0e8ce24c61de23f534688979c79da45b to your computer and use it in GitHub Desktop.
import java.io.*;
import java.util.*;

/*
 * To execute Java, please define "static void main" on a class
 * named Solution.
 *
 * If you need more classes, simply define them inline.
 */

class Solution {
  public static void main(String[] args) {
    ArrayList<String> strings = new ArrayList<String>();
    strings.add("Hello, World!");
    strings.add("Welcome to CoderPad.");
    strings.add("This pad is running Java 8.");

    for (String string : strings) {
      System.out.println(string);
    }
    
    int[][] matrix = {
      {1,2,3,4,5},
      {6,7,8,9,10},
      {11,12,13,14,15},
      {1,1,18,19,1},
      {1,22,23,1,1}
    };
    System.out.println("" + findN(matrix));
  }
  
  public static int findN(int[][] M) {
    if (M == null || M.length < 1 || M[0].length < 1) {
      return -1;
    }
    int N = 0;
    boolean[][] v = new boolean[M.length][M[0].length];
    for (int i = 0; i < M.length; i++) {
      for (int j = 0; j < M[0].length; j++) {
        if (M[i][j] == 1 && v[i][j] == false) {
          render(v, M, i, j);
          N++;
        }
      }
    }
    return N;
  }
  
  public static void render(boolean[][] v, int[][] M, int t, int j) {
    v[t][j] = true;
    int[] x = {0, 0, 1, -1};
    int[] y = {1, -1, 0, 0};
    for (int i = 0; i < 4; i++) {
      int dx = x[i] + t;
      int dy = y[i] + j;
      if (dx > -1 && dy > -1 && dx < M.length && dy < M[0].length) {
        if (M[dx][dy] == 1 && v[dx][dy] == false) {
            render(v, M, dx, dy);
        }
      }
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment