问题是啥啊
更新了
@将客流:
class Program { static void Main(string[] args) { List<List<int>> Array = new List<List<int>>(); //Array.Add(new List<int> { 1, 1, 1, 1, 0 }); //Array.Add(new List<int> { 1, 1, 0, 1, 0 }); //Array.Add(new List<int> { 1, 1, 0, 0, 0 }); //Array.Add(new List<int> { 0, 0, 0, 0, 0 }); Array.Add(new List<int> { 1,1,0,0,0 }); Array.Add(new List<int> { 1,1,0,0,0 }); Array.Add(new List<int> { 0,0,1,0,0 }); Array.Add(new List<int> { 0,0,0,1,1 }); int LnadCount = GetLandCount(Array); } public static int GetLandCount(List<List<int>> Array) { for (int i = 0; i < Array.Count; i++) { Array[i].Insert(0, 0); Array[i].Add(0); } List<int> zeroList = new List<int>(); for (int i = 0; i < Array[0].Count; i++) { zeroList.Add(0); } Array.Insert(0, zeroList); Array.Add(zeroList); List<Land> landList = new List<Land>(); for (int y = 0; y < Array.Count; y++) { for (int x = 0; x < Array[y].Count; x++) { try { if (Array[y][x] == 1) { if (!landList.All(land => land.IsNeighbouredAndSaved(x, y) == true)|| landList.Count == 0) { landList.Add(new Land(x, y)); } } } catch { continue; } } } return landList.Count; } } class Land { public List<Tuple<int,int>> NeighbouredPairs { get; set; } public bool IsNeighbouredAndSaved(int x,int y) { bool result = NeighbouredPairs.Exists(t=>t.Item1==x||t.Item2==y); if (result) { NeighbouredPairs.Add(new Tuple<int, int> ( x, y )); NeighbouredPairs= NeighbouredPairs.Distinct().ToList(); } return result; } public Land(int x, int y) { NeighbouredPairs = new List<Tuple<int, int>>(); NeighbouredPairs.Add(new Tuple<int, int>(x, y)); } }
已测试,over
@将客流: 同时每个岛的陆地 组成也在这个landList里
$arr = array( array(1,0,1,0,0,1,0,1), array(0,1,1,0,1,1,1,0), array(1,0,0,1,0,1,0,0), array(1,0,1,1,0,1,0,1), ); $arr1 = array(); $t = 0; for ($i = 0; $i<4;$i++){ for ($j = 0; $j<8;$j++){ if ($arr[$i][$j] == 0 && $arr1[$i][$j] == null){ $t++; $arr1[$i][$j] = $t; if ($arr[$i+1][$j] == 0){ $arr1[$i+1][$j] = $arr1[$i][$j];} if ($arr[$i][$j+1] == 0){ $arr1[$i][$j+1] = $arr1[$i][$j];} // if ($arr[$i-1][$j] == 0){ $arr1[$i-1][$j] = $arr1[$i][$j];} // if ($arr[$i][$j-1] == 0){ $arr1[$i][$j-1] = $arr1[$i][$j];} } } } return $t -1;
试着写了一下,其实就是判断一个数为0的情况下 ,上下左右是不是也为0,如果是0那就是同一个岛,所以加个数组记录那些是同一个表,判断到通一个岛的时候,数量不增加就行了 其实最好的写法是用递归来写的,写完才发现.
额,好像有点问题,明天再改改吧
DFS 遍历一遍即可