Piotr Czajkowski 2 주 전
부모
커밋
82465164ec
1개의 변경된 파일11개의 추가작업 그리고 27개의 파일을 삭제
  1. 11 27
      06/code.go

+ 11 - 27
06/code.go

@@ -56,9 +56,9 @@ func readInput(file *os.File) (*Point, [][]byte) {
 	return guard, matrix
 }
 
-func walk(guard *Point, matrix [][]byte, xMax, yMax int, visited map[string]int) {
+func walk(guard *Point, matrix [][]byte, xMax, yMax int, visited map[string]int, check func(int) bool) bool {
 	if guard.x < 0 || guard.x > xMax || guard.y < 0 || guard.y > yMax {
-		return
+		return true
 	}
 
 	if matrix[guard.y][guard.x] == '#' {
@@ -67,11 +67,17 @@ func walk(guard *Point, matrix [][]byte, xMax, yMax int, visited map[string]int)
 		guard.direction = (guard.direction + 1) % 4
 	} else {
 		visited[guard.key()]++
+		if check != nil {
+			if check(visited[guard.key()]) {
+				return false
+			}
+		}
+
 		guard.x += directions[guard.direction][0]
 		guard.y += directions[guard.direction][1]
 	}
 
-	walk(guard, matrix, xMax, yMax, visited)
+	return walk(guard, matrix, xMax, yMax, visited, check)
 }
 
 func part1(guard *Point, matrix [][]byte) map[string]int {
@@ -80,32 +86,10 @@ func part1(guard *Point, matrix [][]byte) map[string]int {
 	visited := make(map[string]int)
 
 	newGuard := Point{x: guard.x, y: guard.y}
-	walk(&newGuard, matrix, xMax, yMax, visited)
+	walk(&newGuard, matrix, xMax, yMax, visited, nil)
 	return visited
 }
 
-func walkWithCheck(guard *Point, matrix [][]byte, xMax, yMax int, visited map[string]int) bool {
-	if guard.x < 0 || guard.x > xMax || guard.y < 0 || guard.y > yMax {
-		return true
-	}
-
-	if matrix[guard.y][guard.x] == '#' {
-		guard.x -= directions[guard.direction][0]
-		guard.y -= directions[guard.direction][1]
-		guard.direction = (guard.direction + 1) % 4
-	} else {
-		visited[guard.key()]++
-		if visited[guard.key()] > 4 {
-			return false
-		}
-
-		guard.x += directions[guard.direction][0]
-		guard.y += directions[guard.direction][1]
-	}
-
-	return walkWithCheck(guard, matrix, xMax, yMax, visited)
-}
-
 func part2(guard *Point, matrix [][]byte, expected map[string]int) int {
 	xMax := len(matrix[0]) - 1
 	yMax := len(matrix) - 1
@@ -118,7 +102,7 @@ func part2(guard *Point, matrix [][]byte, expected map[string]int) int {
 
 		visited := make(map[string]int)
 		newGuard := Point{x: guard.x, y: guard.y}
-		if !walkWithCheck(&newGuard, matrix, xMax, yMax, visited) {
+		if !walk(&newGuard, matrix, xMax, yMax, visited, func(a int) bool { return a > 4 }) {
 			count++
 		}