本文主要是介绍力扣第417题测试程序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述:
有一个 m × n 的矩形岛屿,与 太平洋 和 大西洋 相邻。 “太平洋” 处于大陆的左边界和上边界,而 “大西洋” 处于大陆的右边界和下边界。
这个岛被分割成一个由若干方形单元格组成的网格。给定一个 m x n 的整数矩阵 heights , heights[r][c] 表示坐标 (r, c) 上单元格 高于海平面的高度 。
岛上雨水较多,如果相邻单元格的高度 小于或等于 当前单元格的高度,雨水可以直接向北、南、东、西流向相邻单元格。水可以从海洋附近的任何单元格流入海洋。
返回网格坐标 result 的 2D 列表 ,其中 result[i] = [ri, ci] 表示雨水从单元格 (ri, ci) 流动 既可流向太平洋也可流向大西洋 。
示例1:
输入: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
输出: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
示例 2:
输入: heights = [[2,1],[1,2]]
输出: [[0,0],[0,1],[1,0],[1,1]]
力扣题目链接:
https://leetcode.cn/problems/pacific-atlantic-water-flow/
题解思路:深度优先搜索,从边界处进行搜索,寻找符合条件的单元格,从太平洋边上的节点 逆流而上,将遍历过的节点都标记上,从大西洋的边上节点 逆流而长,将遍历过的节点也标记上,最后放入都符合条件的数组即可
下面给出ACM模式代码,包含了核心代码,可以自行验证,主要是熟悉下ACM模式
#include <iostream>
#include <vector>
using namespace std;// 核心代码部分
class Solution {
private:int dir[4][2] = {-1, 0, 0, -1, 1, 0, 0, 1}; // 保存四个方向// 深度优先搜索void dfs(vector<vector<int>>& heights, vector<vector<bool>>& visited, int x, int y) {if (visited[x][y]) return;visited[x][y] = true;for (int i = 0; i < 4; i++) { // 向四个方向遍历long int nextx = x + dir[i][0];long int nexty = y + dir[i][1];// 超过边界if (nextx < 0 || nextx >= heights.size() || nexty < 0 || nexty >= heights[0].size()) continue;// 高度不合适,注意这里是从低向高判断if (heights[x][y] > heights[nextx][nexty]) continue;dfs (heights, visited, nextx, nexty);}return;}public:vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {vector<vector<int>> result;int n = heights.size();int m = heights[0].size();// 记录从太平洋边出发,可以遍历的节点vector<vector<bool>> pacific = vector<vector<bool>>(n, vector<bool>(m, false));// 记录从大西洋出发,可以遍历的节点vector<vector<bool>> atlantic = vector<vector<bool>>(n, vector<bool>(m, false));// 从最上最下行的节点出发,向高处遍历for (int i = 0; i < n; i++) {dfs (heights, pacific, i, 0); // 遍历最左列,接触太平洋 dfs (heights, atlantic, i, m - 1); // 遍历最右列,接触大西 }// 从最左最右列的节点出发,向高处遍历for (int j = 0; j < m; j++) {dfs (heights, pacific, 0, j); // 遍历最上行,接触太平洋dfs (heights, atlantic, n - 1, j); // 遍历最下行,接触大西洋}for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {// 如果这个节点,从太平洋和大西洋出发都遍历过,就是结果if (pacific[i][j] && atlantic[i][j]) result.push_back({i, j});}}return result;}
};int main() {int m, n; // 定义行和列int num; // 输入的不同数字Solution s;vector<vector<int>> res; // 定义一个二维数组// 输入数据while (cin >> m >> n) {if (m == 0 && n == 0) break;res.resize(m, vector<int>(n));for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {cin >> num;res[i][j] = num;}}vector<vector<int>> result = s.pacificAtlantic(res);cout << "输出结果为:" << "["; for (int i = 0; i < result.size(); i++) { cout << "[" << result[i][0] << "," << result[i][1] << "]"; }cout << "]" << endl;}return 0;
}
这篇关于力扣第417题测试程序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!