当前位置: 首页 > news >正文

C语言 | Leetcode C语言题解之第417题太平洋大西洋水流问题

题目:

题解:

static const int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};void bfs(int row, int col, bool ** ocean, const int ** heights, int m, int n) {if (ocean[row][col]) {return;}ocean[row][col] = true;int * queue = (int *)malloc(sizeof(int) * m * n);int head = 0;int tail = 0;queue[tail++] = row * n + col;while (head != tail) {int row = queue[head] / n;int col = queue[head] % n;head++;for (int i = 0; i < 4; i++) {int newRow = row + dirs[i][0], newCol = col + dirs[i][1];if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n && heights[newRow][newCol] >= heights[row][col] && !ocean[newRow][newCol]) {ocean[newRow][newCol] = true;queue[tail++] = newRow * n + newCol;}}}free(queue);
}int** pacificAtlantic(int** heights, int heightsSize, int* heightsColSize, int* returnSize, int** returnColumnSizes){int m = heightsSize;int n = heightsColSize[0];bool ** pacific = (bool **)malloc(sizeof(bool *) * m);bool ** atlantic = (bool **)malloc(sizeof(bool *) * m);for (int i = 0; i < m; i++) {pacific[i] = (bool *)malloc(sizeof(bool) * n);atlantic[i] = (bool *)malloc(sizeof(bool) * n);memset(pacific[i], 0, sizeof(bool) * n);memset(atlantic[i], 0, sizeof(bool) * n);}for (int i = 0; i < m; i++) {bfs(i, 0, pacific, heights, m, n);}for (int j = 1; j < n; j++) {bfs(0, j, pacific, heights, m, n);}for (int i = 0; i < m; i++) {bfs(i, n - 1, atlantic, heights, m, n);}for (int j = 0; j < n - 1; j++) {bfs(m - 1, j, atlantic, heights, m, n);}int ** result = (int **)malloc(sizeof(int *) * m * n);*returnColumnSizes = (int *)malloc(sizeof(int) * m * n);int pos = 0;for (int i = 0; i < m * n; i++) {result[i] = (int *)malloc(sizeof(int) * 2);(*returnColumnSizes)[i] = 2;}for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (pacific[i][j] && atlantic[i][j]) {result[pos][0] = i;result[pos][1] = j;pos++;}}free(pacific[i]);free(atlantic[i]);}free(pacific);free(atlantic);*returnSize = pos;return result;
}

http://www.mrgr.cn/news/30668.html

相关文章:

  • IBM中国研发中心撤离背后的IT行业人才挑战与产业未来展望
  • 茴香豆:企业级知识问答工具实践闯关任务
  • SalescustomerController
  • Agent Zero
  • 谷歌论文提前揭示o1模型原理:AI大模型竞争或转向硬件
  • Golang | Leetcode Golang题解之第417题太平洋大西洋水流问题
  • 视觉 注意力机制——通道注意力、空间注意力、自注意力、交叉注意力
  • C# 访问Access存取图片
  • 软件安全最佳实践:首先关注的地方
  • 【macOS】【Python】安装Python到虚拟环境的命令
  • 版本控制之Git
  • 电力施工作业安全行为检测图像数据集
  • 算法打卡 Day41(动态规划)-理论基础 + 斐波那契数 + 爬楼梯 + 使用最小花费爬楼梯
  • MATLAB矩阵下标引用
  • 图数据库之HugeGraph
  • 深度学习笔记(8)预训练模型
  • Linux文件系统
  • 8.1差分边缘检测
  • 介绍几个AI生成视频的工具
  • 新发布的OpenAI o1生成式AI模型在强化学习方面迈出了重要的一步