Created
September 2, 2013 02:57
-
-
Save leepro/6408856 to your computer and use it in GitHub Desktop.
2D with different colours. Counting countries.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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