Kth Smallest Number in Sorted Matrix (정렬 행렬 의 작은 것 부터 큰 것 까지 k 개 수)

http://www.lintcode.com/en/problem/kth-smallest-number-in-sorted-matrix/?rand=true 질서정연 한 집합의 Prority Queue 를 참조 하 십시오
import java.util.PriorityQueue;

public class Solution {
    /*
     * @param matrix: a matrix of integers
     * @param k: An integer
     * @return: the kth smallest number in the matrix
     */
    public int kthSmallest(int[][] matrix, int k) {
        // write your code here
//                  ,         。      ,                  
        PriorityQueue priorityQueue = new PriorityQueue<>();
        priorityQueue.add(new Node(0, 0, matrix[0][0]));
//                  ,      
        boolean[][] visited = new boolean[matrix.length][matrix[0].length];
        visited[0][0] = true;
        for (int i = 0; i < k - 1; i++) {
//                ,    ,  k-1 。
            Node first = priorityQueue.poll();
            add(priorityQueue, first.x, first.y, matrix, visited);
        }
        return priorityQueue.poll().value;
    }

    private void add(PriorityQueue set, int i, int j, int[][] matrix, boolean[][] visited) {
        if (i < matrix.length - 1 && !visited[i + 1][j]) {
            Node e = new Node(i + 1, j, matrix[i + 1][j]);
            set.add(e);
            visited[i + 1][j] = true;
        }
        if (j < matrix[0].length - 1 && !visited[i][j + 1]) {
            Node e = new Node(i, j + 1, matrix[i][j + 1]);
            set.add(e);
            visited[i][j + 1] = true;
        }
    }

    private class Node implements Comparable {
        int x;
        int y;
        int value;

        Node(int x, int y, int value) {
            this.x = x;
            this.y = y;
            this.value = value;
        }

        @Override
        public int compareTo(Node o) {
            return value - o.value;
        }
    }
}

좋은 웹페이지 즐겨찾기