首页 > 代码库 > Java-寻找矩阵连通域个数

Java-寻找矩阵连通域个数

给定一个矩阵,寻找连通域个数:前后左右相同为连通

ex:

0 1 0 1

0 1 1 1

0 0 1 0

0 1 0 0

输出2

利用深度搜索思路:

 1     public static int getCount(int[][] A) { 2         int result = 0; 3         for (int i = 0; i < A.length; i++) { 4             for (int j = 0; j < A[0].length; j++) { 5                 if (A[i][j] == 1) { 6                     result++; 7                     erase(A, i, j); 8                 } 9             }10         }11         return result;12     }13 14     public static void erase(int[][] A, int i, int j) {15         A[i][j] = 0;16         while (i - 1 >= 0 && A[i - 1][j] == 1) {17             erase(A, i - 1, j);18         }19         while (i + 1 < A.length && A[i + 1][j] == 1) {20             erase(A, i + 1, j);21         }22         while (j - 1 >= 0 && A[i][j - 1] == 1) {23             erase(A, i, j - 1);24         }25         while (j + 1 < A[0].length && A[i][j + 1] == 1) {26             erase(A, i, j + 1);27         }28         29     }