It is important in many applications of 3D and higher dimensional segmentation that the resulting segments of voxels are not required to have only one connected component, as in some of extant methods. Indeed, it is generally necessary to be able to automatically determine the appropriate number of connected components. More generally, for a larger class of applications, the segments should have no topological restrictions at all. For instance, each connected component should be allowed to have as many holes as appropriate to fit the data. We propose a method based on a graph algorithm to automatically segment 3D and higher-dimensional images into two segments without user intervention, with no topological restriction on the solution, and in such a way that the solution is optimal under a precisely defined optimization criterion.