天池在线编程 2020国庆八天乐 - 4. 生成更大的陆地(BFS)
生活随笔
收集整理的這篇文章主要介紹了
天池在线编程 2020国庆八天乐 - 4. 生成更大的陆地(BFS)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
1. 題目
https://tianchi.aliyun.com/oj/118289365933779217/122647324262601668
LeetCode 上也有該題 827. 最大人工島
描述
在一個0和1的2D網格中,我們最多將一個0改為1。
之后,最大島嶼的大小是多少? (一個島是四個方向上互相連接的一組1)。
2. 解題
class Solution { public:/*** @param grid: * @return: nothing*/int n, color = 2, maxarea = 0;unordered_map<int, int> m;// color, areavector<vector<int>> dir = {{1,0},{0,1},{-1,0},{0,-1}};int largestIsland(vector<vector<int>> &grid) {// write your code heren = grid.size();for(int i = 0, j; i < n; ++i){for(j = 0; j < n; ++j){if(grid[i][j]==1){color++;bfs(grid, i, j, color);}}}for(int i = 0, j; i < n; ++i){for(j = 0; j < n; ++j){if(grid[i][j] == 0){unordered_set<int> s;//記錄四周的顏色有幾種int area = 1;for(int k = 0; k < 4; ++k){int x = i + dir[k][0];int y = j + dir[k][1];if(x>=0 && x < n && y>=0 && y < n && !s.count(grid[x][y])){s.insert(grid[x][y]);//插入顏色area += m[grid[x][y]];//加入這種顏色的陸地面積}}maxarea = max(maxarea, area);}}}return maxarea;}void bfs(vector<vector<int>> &grid, int i, int j, int color){int area = 0, x, y;queue<pair<int, int>> q;q.push({i,j});grid[i][j] = color;while(!q.empty()){x = q.front().first;y = q.front().second;q.pop();area++;for(int k = 0; k < 4; ++k){i = x + dir[k][0];j = y + dir[k][1];if(i >= 0 && i < n && j >= 0 && j < n && grid[i][j]==1){q.push({i, j});grid[i][j] = color;}}}m[color] = area;//記錄這個顏色的陸地的面積maxarea = max(maxarea, area);} };我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的天池在线编程 2020国庆八天乐 - 4. 生成更大的陆地(BFS)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天池 在线编程 寻找字母(计数)
- 下一篇: LeetCode 1312. 让字符串成