391.perfect-rectangle.go 1001 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. type pair struct {
  2. _1 int
  3. _2 int
  4. }
  5. func isRectangleCover(rectangles [][]int) bool {
  6. w, a, s, d := rectangles[0][3], rectangles[0][0], rectangles[0][1], rectangles[0][2]
  7. area := 0
  8. m := make(map[pair]bool)
  9. for i := range rectangles {
  10. cw, ca, cs, cd := rectangles[i][3], rectangles[i][0], rectangles[i][1], rectangles[i][2]
  11. w, a, s, d = maxInt(w, cw), minInt(a, ca), minInt(s, cs), maxInt(d, cd) // Record the max rectangle
  12. area += (cw - cs) * (cd - ca)
  13. put(&m, ca, cw) // If the coverage is perfect, all points appear in pair except tl, tr, bl and br.
  14. put(&m, cd, cw)
  15. put(&m, ca, cs)
  16. put(&m, cd, cs)
  17. }
  18. return m[pair{a, w}] && m[pair{d, w}] && m[pair{a, s}] && m[pair{d, s}] && len(m) == 4 && area == (w-s)*(d-a)
  19. }
  20. func put(m *map[pair]bool, x, y int) {
  21. p := pair{x, y}
  22. if _, ok := (*m)[p]; ok {
  23. delete(*m, p)
  24. } else {
  25. (*m)[p] = true
  26. }
  27. }
  28. func maxInt(x, y int) int {
  29. if x < y {
  30. return y
  31. }
  32. return x
  33. }
  34. func minInt(x, y int) int {
  35. if x < y {
  36. return x
  37. }
  38. return y
  39. }