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;
    }
};
相关推荐
远瞻。25 分钟前
【论文阅读】人脸修复(face restoration ) 不同先验代表算法整理2
论文阅读·算法
先做个垃圾出来………3 小时前
哈夫曼树(Huffman Tree)
数据结构·算法
phoenix@Capricornus5 小时前
反向传播算法——矩阵形式递推公式——ReLU传递函数
算法·机器学习·矩阵
Inverse1625 小时前
C语言_动态内存管理
c语言·数据结构·算法
数据与人工智能律师5 小时前
虚拟主播肖像权保护,数字时代的法律博弈
大数据·网络·人工智能·算法·区块链
wuqingshun3141596 小时前
蓝桥杯 16. 外卖店优先级
c++·算法·职场和发展·蓝桥杯·深度优先
YouQian7727 小时前
2025春训第十九场
算法
CodeJourney.7 小时前
基于MATLAB的生物量数据拟合模型研究
人工智能·爬虫·算法·matlab·信息可视化
Epiphany.5567 小时前
素数筛(欧拉筛算法)
c++·算法·图论
爱吃涮毛肚的肥肥(暂时吃不了版)7 小时前
项目班——0510——JSON网络封装
c++·算法·json