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;
    }
};
相关推荐
黑岚樱梦38 分钟前
代码随想录打卡day23:435.无重叠区间
算法
Kuo-Teng1 小时前
Leetcode438. 找到字符串中所有字母异位词
java·算法·leetcode
gihigo19982 小时前
MATLAB使用遗传算法解决车间资源分配动态调度问题
算法·matlab
墨染点香2 小时前
LeetCode 刷题【138. 随机链表的复制】
算法·leetcode·链表
却道天凉_好个秋2 小时前
目标检测算法与原理(一):迁移学习
算法·目标检测·迁移学习
兮山与3 小时前
算法24.0
算法
晓北斗NorSnow3 小时前
机器学习核心算法与学习资源解析
学习·算法·机器学习
hans汉斯4 小时前
【计算机科学与应用】基于BERT与DeepSeek大模型的智能舆论监控系统设计
大数据·人工智能·深度学习·算法·自然语言处理·bert·去噪
多喝开水少熬夜5 小时前
损失函数系列:focal-Dice-vgg
图像处理·python·算法·大模型·llm