LC-695 最大区域的岛
目标:
输入一个二维数组,0和边界代表大海,1代表岛屿的面积,岛的连接仅由上下左右四个方向相连,试找出最大岛屿的面积。
思路:
使用深搜算法,便利二位数组,当找到一个值为1的pixel,开始进行深搜,搜索与其相连的岛屿面积,对添加进栈的pixel标记为0,代表已搜索。最后比较留下最大岛屿的面积。
代码:
1 class Solution { 2 public: 3 int maxAreaOfIsland(vector<vector<int>>& grid) { 4 int direction[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; 5 int height = grid.size(); 6 int width = grid[0].size(); 7 int max = 0; 8 for (int i = 0; i < height; i++) { 9 for (int j = 0; j < width; j++) { 10 // 找到岛屿的一个pixel 11 if (grid[i][j] == 1) { 12 // 为dfs进行初始化 13 int count = 0; 14 vector<int*> stack; 15 int* init = new int[2]; 16 init[0] = i; 17 init[1] = j; 18 stack.push_back(init); 19 // 标记该点已搜索 20 grid[i][j] = 0; 21 // 开始dfs 22 while (!stack.empty()) { 23 // 出栈 24 count++; 25 int* current = stack.back(); 26 int x = current[0]; 27 int y = current[1]; 28 delete current; 29 stack.pop_back(); 30 // 遍历该pixel的四个方向 31 for (int k = 0; k < 4; k++) { 32 int new_x = x + direction[k][0]; 33 int new_y = y + direction[k][1]; 34 if (new_x >= 0 && new_x < height && new_y >= 0 && new_y < width) { 35 if (grid[new_x][new_y] == 1) { 36 int* v = new int[2]; 37 v[0] = new_x; 38 v[1] = new_y; 39 stack.push_back(v); 40 // 对已入栈的pixel标记为已搜索 41 grid[new_x][new_y] = 0; 42 } 43 } 44 } 45 } 46 47 if (count > max) 48 max = count; 49 } 50 } 51 } 52 return max; 53 } 54 };