Beispiel #1
0
  public int TrapWater2(int[,] heights) {
    if(heights == null || heights.GetLength(0) == 0 || heights.GetLength(1) == 0) return 0;

    var pq = new PriorityQueue<Cell>((a,b) -> Integer.Compare(a.ht,b.ht));

    int m = heights.GetLength(0);
    int n = heights.GetLength(1);
    bool[,] visited = new bool[m,n];

    // 1. Add all border cells into pq
    for(int i = 0; i < m; i++) {
      visited[i,0] = true;
      visited[i,n-1] = true;
      pq.offer(new Cell(i,0,heights[i,0]);
      pq.offer(new Cell(i,n-1,heights[i,n-1]);
    }

    for(int i = 0; i < n; i++) {
      visited[0,i] = true;
      visited[m-1,i] = true;
      pq.offer(new Cell(i,0,heights[0,i]);
      pq.offer(new Cell(i,n-1,heights[m-1,i]);
    }

    int max = Int32.MinValue, sum = 0;
    // 2. Pick smallest cell, visit neighbors
    int[,] dirs = new int[,] {{-1,0}, {1,0}, {0,1}, {0,-1}};
    while(pq.Count != 0) {
      Cell curr = pq.poll();
      max = Math.Max(curr.ht, max);
      if(curr.ht < max) {
        sum += max - curr.ht;
      }

      for(int[] dir in dirs) {
        int row = cell.row + dir[0];
        int col = cell.col + dir[1];

        if(row >= 0 && row < m && col >= 0 && col < n && !visited[row,col]) {
          visited[row,col] = true;
          pq.offer(new Cell(row, col, heights[row,col]));
        }
      }
    }

    return sum;
  }
Beispiel #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns>a < b: - 1; a == b: 0; a > b: == 1</b></returns>
        public static int Compare(Rational a, Rational b)
        {
            Natural lcm = Natural.LCM(a.Denominator, b.Denominator);

            return(Integer.Compare(a.Numerator * lcm / a.Denominator, b.Numerator * lcm / a.Denominator));
        }
Beispiel #3
0
 private static int Compare(int x, int y)
 {
     return(Integer.Compare(x, y));
 }