code.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. type Point struct {
  9. y, x int
  10. value byte
  11. }
  12. func (p *Point) key() string {
  13. return fmt.Sprintf("%d_%d", p.y, p.x)
  14. }
  15. func readInput(file *os.File) [][]byte {
  16. scanner := bufio.NewScanner(file)
  17. var matrix [][]byte
  18. for scanner.Scan() {
  19. line := scanner.Text()
  20. if line == "" {
  21. break
  22. }
  23. matrix = append(matrix, []byte(line))
  24. }
  25. return matrix
  26. }
  27. var directions [][]int = [][]int{
  28. {0, -1}, {1, 0}, {0, 1}, {-1, 0},
  29. }
  30. func getPlots(current Point, matrix [][]byte, xMax, yMax int) []Point {
  31. var plots []Point
  32. for _, direction := range directions {
  33. plot := Point{x: current.x + direction[0], y: current.y + direction[1]}
  34. if plot.x >= 0 && plot.x < xMax &&
  35. plot.y >= 0 && plot.y < yMax && matrix[plot.y][plot.x] == current.value {
  36. plot.value = matrix[plot.y][plot.x]
  37. plots = append(plots, plot)
  38. }
  39. }
  40. return plots
  41. }
  42. func getRegion(start Point, matrix [][]byte, xMax, yMax int, checked map[string]bool) []Point {
  43. plots := []Point{start}
  44. var region []Point
  45. for len(plots) > 0 {
  46. current := plots[0]
  47. plots = plots[1:]
  48. if !checked[current.key()] {
  49. region = append(region, current)
  50. }
  51. checked[current.key()] = true
  52. newPlots := getPlots(current, matrix, xMax, yMax)
  53. for _, plot := range newPlots {
  54. if !checked[plot.key()] {
  55. plots = append(plots, plot)
  56. }
  57. }
  58. }
  59. return region
  60. }
  61. func part1(matrix [][]byte) int {
  62. xMax := len(matrix[0])
  63. yMax := len(matrix)
  64. checked := make(map[string]bool)
  65. for y := range matrix {
  66. for x := range matrix[y] {
  67. current := Point{x: x, y: y, value: matrix[y][x]}
  68. if !checked[current.key()] {
  69. region := getRegion(current, matrix, xMax, yMax, checked)
  70. fmt.Println(region)
  71. }
  72. }
  73. }
  74. return 0
  75. }
  76. func main() {
  77. if len(os.Args) < 2 {
  78. log.Fatal("You need to specify a file!")
  79. }
  80. filePath := os.Args[1]
  81. file, err := os.Open(filePath)
  82. if err != nil {
  83. log.Fatalf("Failed to open %s!\n", filePath)
  84. }
  85. matrix := readInput(file)
  86. fmt.Println(part1(matrix))
  87. }