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;
    }
};
相关推荐
荒诞硬汉2 分钟前
数组常见算法
java·数据结构·算法
少许极端2 分钟前
算法奇妙屋(二十四)-二维费用的背包问题、似包非包问题、卡特兰数问题(动态规划)
算法·动态规划·卡特兰数·二维费用背包·似包非包
Z1Jxxx7 分钟前
日期日期日期
开发语言·c++·算法
万行13 分钟前
机器学习&第五章生成式生成器
人工智能·python·算法·机器学习
罗湖老棍子15 分钟前
【模板】并查集(洛谷P3367)
算法·图论·并查集
_OP_CHEN22 分钟前
【算法基础篇】(四十五)裴蜀定理与扩展欧几里得算法:从不定方程到数论万能钥匙
算法·蓝桥杯·数论·算法竞赛·裴蜀定理·扩展欧几里得算法·acm/icpc
shangjian00732 分钟前
AI大模型-机器学习-算法-线性回归
人工智能·算法·机器学习
2301_800256111 小时前
B+树:数据库的基石 R树:空间数据的索引专家 四叉树:空间划分的网格大师
数据结构·数据库·b树·机器学习·postgresql·r-tree
mjhcsp1 小时前
C++ KMP 算法:原理、实现与应用全解析
java·c++·算法·kmp
lizhongxuan1 小时前
Manus: 上下文工程的最佳实践
算法·架构