嗨我想執行一個代碼,它返回1和1的矩陣中1的島的最大長度。Java:矩陣中最長的島
在1和0的矩陣中,如果矩陣的兩個相鄰元素是1,那麼它們可以形成一個島。矩陣可以有多個島。相鄰元素可以是水平的,垂直的或對角線的。
這裏是邏輯:
import java.util.Arrays;
public class IslandMatrix {
static final int ROW = 5, COL = 5;
static int max_1 = 0;
public boolean isSafe(int M[][], int row, int col,
boolean visited[][])
{
if((row >= 0) && (row < ROW) &&
(col >= 0) && (col < COL) &&
(M[row][col]==1 && !visited[row][col])){
return true;
}
return false;
}
int DFS(int M[][], int row, int col, boolean visited[][])
{
max_1 = max_1+1;
int rowNbr[] = new int[] {-1, 0, 1, -1, 1, -1, 0, 1};
int colNbr[] = new int[] {-1, -1, -1, 0, 0, 1, 1, 1};
visited[row][col] = true;
for (int k = 0; k < 8; ++k)
if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)){
DFS(M, row + rowNbr[k], col + colNbr[k], visited);
}
return max_1;
}
int countIsland(int M[][])
{
boolean visited[][] = new boolean[ROW][COL];
//int count = 0;
int temp = 0;
int max =0;
for (int i = 0; i < ROW; ++i)
for (int j = 0; j < COL; ++j){
max_1 = 0;
if (M[i][j]==1 && !visited[i][j]){
temp = DFS(M, i, j, visited);
if(temp>max){
max = temp;
}
}
}
return max;
}
public static void main (String[] args) throws java.lang.Exception
{
int M[][]= new int[][] {{0, 1, 0, 1, 0},
{0, 0, 1, 1, 1},
{1, 0, 1, 1, 0},
{0, 1, 0, 0, 0},
{0, 0, 1, 0, 1}
};
IslandMatrix I = new IslandMatrix();
System.out.println("Max length of island is: "+ I.countIsland(M));
}
}
考慮:
{0, 1, 0, 1, 0}
{0, 0, 1, 1, 1}
{1, 0, 1, 1, 0}
{0, 1, 0, 0, 0}
{0, 0, 1, 0, 1}
在這種情況下最長的島與1的跟隨如下的指數路徑: (0,1) - >( 1,2) - >(1,3) - >(0,2) - >(1,4) - >(2,3) - >(2,2) - >(3,1) - >(2 ,0)
以這種方式結果應該是9,但我得到的結果爲10.
任何人都可以用適當的邏輯幫助我。
答案不應該是10嗎? (0,1),(0,3),(1,2),(1,3),(1,4),(2,0),(2,2),(2, 3),(3,1),(4,2) – MicD
[爲什麼「有人可以幫我嗎?」不是一個實際的問題?](http://meta.stackoverflow.com/q/284236/18157) –
有你檢查[算法的這個例子](http://stackoverflow.com/questions/27736983/count-islands-of-zeros-in-a-matrix?rq=1) –