Skip to content

Instantly share code, notes, and snippets.

@leepro
Created September 2, 2013 02:57
Show Gist options
  • Save leepro/6408856 to your computer and use it in GitHub Desktop.
Save leepro/6408856 to your computer and use it in GitHub Desktop.
2D with different colours. Counting countries.
class Solution {
int[][] visited = null;
int tot = 0;
public int solution(int[][] A) {
int N = A.length;
int M = A[0].length;
visited = new int[N][M];
for(int n = 0; n < N; n++) {
for(int m = 0; m < M; m++) {
if(visited[n][m]==0) {
search(A, A[n][m], n, m);
tot++;
}
}
}
return tot;
}
public void search(int[][] A, int color, int n, int m) {
if(visited[n][m]==1) return;
visited[n][m] = 1;
try {
if(color == A[n+1][m]) search(A, color, n+1, m);
} catch(Exception e) {}
try {
if(color == A[n-1][m]) search(A, color, n-1, m);
} catch(Exception e) {}
try {
if(color == A[n][m-1]) search(A, color, n, m-1);
} catch(Exception e) {}
try {
if(color == A[n][m+1]) search(A, color, n, m+1);
} catch(Exception e) {}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment