public class Solution { public int MaxAreaOfIsland(int[,] grid) { var row = grid.GetLength(0);//8 var coloum = grid.GetLength(1);//13 bool[,] Visited = new bool[row, coloum]; Queue<KeyValuePair<int, int>> Q = new Queue<KeyValuePair<int, int>>(); int max = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < coloum; j++) { int island = 0; if (!Visited[i, j]) { Q.Enqueue(new KeyValuePair<int, int>(i, j)); } while (Q.Any()) { var pair = Q.Dequeue(); if (Visited[pair.Key, pair.Value])//此节点已经处理过 { continue; } else { Visited[pair.Key, pair.Value] = true;//处理当前节点 if (grid[pair.Key, pair.Value] == 1) { island++; //将此节点是1,则将这个节点的上下左右都取出来, var up_point = new KeyValuePair<int, int>(pair.Key - 1, pair.Value); var left_point = new KeyValuePair<int, int>(pair.Key, pair.Value - 1); var down_point = new KeyValuePair<int, int>(pair.Key + 1, pair.Value); var right_point = new KeyValuePair<int, int>(pair.Key, pair.Value + 1); //如果是合法数值,则进队 if (up_point.Key >= 0 && !Visited[up_point.Key, up_point.Value] && grid[up_point.Key, up_point.Value] == 1) { Q.Enqueue(up_point); } if (left_point.Value >= 0 && !Visited[left_point.Key, left_point.Value] && grid[left_point.Key, left_point.Value] == 1) { Q.Enqueue(left_point); } if (down_point.Key <= row - 1 && !Visited[down_point.Key, down_point.Value] && grid[down_point.Key, down_point.Value] == 1) { Q.Enqueue(down_point); } if (right_point.Value <= coloum - 1 && !Visited[right_point.Key, right_point.Value] && grid[right_point.Key, right_point.Value] == 1) { Q.Enqueue(right_point); } } } } //当前岛屿查询结束,更新最大岛 if (max < island) { max = island; } } } return max; } }
本题属于分支限界的题目,广度优先进行搜索。利用访问的数组Visited,记录已经走过的路径,以减少重复计算。