401 · 排序矩阵中的从小到大第k个数

链接:LintCode 炼码 - ChatGPT!更高效的学习体验!

题解: 九章算法 - 帮助更多程序员找到好工作,硅谷顶尖IT企业工程师实时在线授课为你传授面试技巧

cpp 复制代码
class Solution {
public:
    /**
     * @param matrix: a matrix of integers
     * @param k: An integer
     * @return: the kth smallest number in the matrix
     */
class Node {
public:
    Node(int v, int i):val(v),index(i) {

    }
    bool operator < (const Node& node) const {
        return val > node.val ? true : false;
    }
    int val;
    int index;
};
    int kthSmallest(vector<vector<int>> &matrix, int k) {
        // write your code here
        int m = matrix.size();
        if (m <= 0) {
            return 0;
        }
        int n = matrix[0].size();
        if (n <= 0) {
            return 0;
        }
        std::vector<bool> distance(m*n, false);
        distance[0] = true;
        std::priority_queue<Node> que;
        que.push(Node(matrix[0][0], 0)); 
        int i = 1;
        std::vector<std::vector<int>> direction{{0, 1}, {1, 0}};
        while (!que.empty()) {
            auto f = que.top();
            que.pop();
            if (i >= k) {
                return f.val;
            }
            for (int j = 0; j < direction.size(); ++j) {
                int next_row = f.index / n + direction[j][0];
                int next_col = f.index % n + direction[j][1];
                if (next_row < 0 || next_col < 0 || next_row >= m || next_col >= n) {
                    continue;
                }
                int node = next_row * n + next_col;
                if (distance[node]) {
                    continue;
                }
                que.push(Node(matrix[next_row][next_col], node));
                distance[node] = true;
            }
            ++i;
        }
        return -1;
    }
};
相关推荐
闲人编程20 小时前
图像去雾算法:从物理模型到深度学习实现
图像处理·人工智能·python·深度学习·算法·计算机视觉·去雾
咔咔学姐kk20 小时前
大模型微调技术宝典:Transformer架构,从小白到专家
人工智能·深度学习·学习·算法·transformer
haogexiaole21 小时前
Dijkstra 算法
算法
papership1 天前
【入门级-算法-6、排序算法: 插入排序】
数据结构·算法·排序算法
HAH-HAH1 天前
【蓝桥杯 2024 国 Java A】粉刷匠小蓝
c++·学习·数学·算法·职场和发展·蓝桥杯·组合数学
得意霄尽欢1 天前
Redis之底层数据结构
数据结构·数据库·redis
I'm a winner1 天前
第五章:Python 数据结构:列表、元组与字典(二)
数据结构·python
我是是是是是西红柿1 天前
游戏中的展销系统使用的数据结构
数据结构·游戏
hweiyu001 天前
C++设计模式,高级开发,算法原理实战,系统设计与实战(视频教程)
c++·算法·设计模式
爱吃烤鸡翅的酸菜鱼1 天前
【Redis】常用数据结构之Hash篇:从常用命令到使用场景详解
数据结构·数据库·redis·后端·缓存·哈希算法