1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| public class flowerNumber { public static void main(String[] args){ int[][] studentCube={{0,0,1,1,1}, {1,0,1,0,0}, {1,1,1,0,1}, {0,0,0,0,0}, {1,1,0,1,1}}; System.out.print("Number of flowers is "+solution(studentCube)); } public static int solution(int[][] studentCube){ int flowerNum=0; for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ if(studentCube[i][j]==0) continue; flowerNum++; tagFemaleToMale(studentCube,i,j); } } return flowerNum; } public static void tagFemaleToMale(int[][] studentCube,int i,int j){ studentCube[i][j]=0; if(i<4){ if(studentCube[i+1][j]==1) tagFemaleToMale(studentCube,i+1,j); } if(j<4){ if(studentCube[i][j+1]==1) tagFemaleToMale(studentCube,i,j+1); } if(i>0){ if(studentCube[i-1][j]==1) tagFemaleToMale(studentCube,i-1,j); } if(j>0){ if(studentCube[i][j-1]==1) tagFemaleToMale(studentCube,i,j-1); } }
}
|