-
Notifications
You must be signed in to change notification settings - Fork 0
1-sep037 #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
giljihun
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
import Foundation
guard let input = readLine(),
let N = Int(input.split(separator:" ")[0]),
let M = Int(input.split(separator:" ")[1]) else { exit(0) }
var rectangle: [[Int]] = []
for _ in 0..<N {
guard let line = readLine() else { exit(0) }
/* MARK: - NOTE
여기서 Int($0)로 하려했지만, line을 순회하면 Character 타입이 나오기 때문에 String으로의 변환이 필요함.
추가적으로 .compactMap은 .map과 다르게
👉 nil은 자동으로 제거하고, 언래핑된 값만 담아줌
*/
let row = line.compactMap { Int(String($0)) }
rectangle.append(row)
}
/* MARK: - Solution
1. 왼꼭을 기준점으로 하나하나 잡아.
2. 거기 기준으로 사이즈를 넓혀가면서 정사각형 크기만큼 체크해버려.
3. 정사각형이 된다면 maxSize 갱신.
*/
var maxSize: Int = 1
for row in 0..<N {
for col in 0..<M {
for size in 1...min(N, M) {
// size = 2 라면, 실제 정사각형 한 변의 길이는 3. (2칸 떨어졌으니까 → 3칸)
let endRow = row + size - 1
let endCol = col + size - 1
if endRow >= N || endCol >= M { break }
let topLeft = rectangle[row][col]
let topRight = rectangle[row][endCol]
let botLeft = rectangle[endRow][col]
let botRight = rectangle[endRow][endCol]
let corners = [topLeft, topRight, botLeft, botRight]
if Set(corners).count == 1 {
let newSize = size * size
maxSize = max(maxSize, newSize)
}
}
}
}
print(maxSize)저도 비슷하게 풀었는데 저는 정사각형 찾는 로직을 생각하기가 넘 어려웠어요.
다행히 로직이 같은 것 같아서 다행입니다.
그리고 풀고보니,
사실 정사각형 사이즈가 중요하고 값은 중요하지 않은 것 같아서
입력을 더 쉽게 받을 수도 있을 것 같아요!
let row = Array(line)
입력: 42101 ->
["4", "2", "1", "0", "1"]이런식으로 Array를 써서 Int로 변환하지말고 바로 배열로 만들어줘도,
어차피 나중에 값이 같은지만 비교하니까 이게 더 괜찮은 것 같애요!~!
sep037/구현/BOJ_1051.swift
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
let row = readLine()!.map {Int($0)!} // 이곳이 바로 문제의 부분 !여기 부분 오류 안나시나요??
let row = readLine()!.map {Int(String($0))!} // 이곳이 바로 문제의 부분 !Int()는 String 타입만 받을 수 있는데, map()이나 compactMap()은 String을 받고 각 문자를 Character로 봐서
이를 String으로 변환을 하지 않으면 Int()로 래핑이 안되는걸로 알고있어서요!!
뭐지 하고 돌려봤는데 저는 오류가 뜨네요..?? 버전마다 차이가 있나요 이거.. 아시는분.. ㅠㅠ
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
헉 이거 제가 잘못 올렸어요
백준에는 저렇게 풀어놓고 ㅋㅋㅋㅋ
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
어려웡
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@sep037 그렇군뇨 ㅋㅋㅋ 굿굿!!
YooGyeongMo
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
정사각형 구하는 아이디어를 다들 어떻게 생각해내셨나요? 저는 저만의 한계를 느꼈답니다...
sep037/구현/BOJ_1051.swift
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
오 글로니 ! 최소 크기부터 하셨군요. 저는 사실 정사각형을 알아내는게 쉽지않아서 열받아서 있다가, 제일 큰것에서부터 체크하면서 내려오면 어떨까해서
min_range = min(n,m) - 1
max_value = 1
for i in range(n):
for j in range(m):
for l in range(min_range,0,-1):
if i+l < n and j+l < m:
if graph[i][j] == graph[i+l][j] == graph[i][j+l] == graph[i+l][j+l]:
max_value = max(max_value, (l+1)**2)
break
print(max_value)
파이썬 코드이긴 하지만, 먼저 정사각형이 되려면 행과 열중에서 더 작은 숫자 바이 더 작은 숫자하면 그게 아마 정사각형 변의 최고 수치지않을까? 거기서부터 넓이구해서 계속 갱신해나가면 뭔가 빨리 나오지 않을까? 해서 했는데 아마 결국엔 완탐으로 구현을 해서 어차피 첫번째가 가장 큰거라면 아랫것들은 비교하지 않는다면 어떨까 싶네요.
끄윽 ... 쉬운 문제라고 하지만 저한텐 어려웠는데 정말 갈길이 멀군요.. 인덱스 장난과 마지막 for문의 변길이 측정이 아이디어 도출이 많이 어려웠네요 ...
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
엄청 깔끔하게 잘푸셨네요 !
푸는 방식에서 큰 차이는 없고, 저도 데미안과 거의 동일한 코드입니다 !
저는 둘 사이의 min(N,M)을 기준으로 큰 변부터 깎아가면서 판단해줄것인지, 작은값부터 올라가면서 판단해줄 것인지가 차이가 있는 것 같네요! 좀 코드가 정신이 없을 수도 있습니다..!
import Foundation
func solution(_ N: Int, _ M: Int, _ graph: [[Int]]) -> Int {
let LEN = min(N, M)
for width in stride(from: LEN - 1, to: 0, by: -1) {
for i in 0 ..< N - width {
for j in 0 ..< M - width {
let standard = graph[i][j]
if standard == graph[i][j + width] {
if standard == graph[i + width][j] && standard == graph[i + width][j + width] {
return (width + 1) * (width + 1)
}
}
}
}
}
return 1
}
// 지난번에 입력받은 부분 재활용
let NM = readLine()!.split(separator: " ").map { Int($0)! }
let N = NM[0]
let M = NM[1]
var arr: [[Int]] = []
for _ in 0 ..< N {
arr.append(readLine()!.map { Int(String($0))! })
}
print(solution(N, M, arr))There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
핀 제 입력받기 습득하신건가요 전 n, m만 받도록 했는데 핀처럼하는게 함수 의도가 명확해지는 것 같네요. 잘 배우고 갑니다^^
전 아래처럼 했어요. 함수 의도 고려하면서 짜야겠습니다 다음부터.
func solution(_ n: Int, _ m: Int) -> Int {
// 생략
let nm = readLine()!.split(separator: " ").map { Int($0)! }
let n = nm[0]
let m = nm[1]
print(solution(n, m))|
다들 역시 비슷하네요 브루트포스라 그런가.. 저도 비슷한 방식으로 풀었습니다!! let NM = readLine()!.split(separator: " ").map{ Int(String($0))! }
let N = NM[0]
let M = NM[1]
var board: [[Int]] = []
var result = 1
for _ in 0..<N {
board.append(readLine()!.map { Int(String($0))!} )
}
for size in 0..<min(N, M){
for i in 0..<N {
for j in 0..<M {
if i + size >= N || j + size >= M { continue }
let a = board[i][j]
let b = board[i][j+size]
let c = board[i+size][j]
let d = board[i+size][j+size]
if a == b && a == c && a == d {
let resultSize = size + 1
result = resultSize * resultSize
}
}
}
}
print(result) |
sep037/구현/BOJ_1051.swift
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
함수로 만든건 좋은데 이부분에서
n,m을 다시 grid를 기준으로 count해서 시간을 조금 늘리는 것 같아서
차라리 매개변수로 받거나 main에서 푸는게 시간복잡도가 빡빡한 문제에서는 좋을 것 같아요!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
복잡도 관련해서 항상 효율적인 코드 짜는 게 어려운 것 같아요 🥹
많이 풀어서 감을 올려볼게요 , ,
MuchanKim
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
문제 풀고 리뷰를 왜 안달았을까요!! 풀기전에 리뷰를 봐버려서 브루트포스인걸 아니까 그나마 수월하게 풀었습니다!(그래도 40분쯤 걸린 듯??) 고생하셨어요!
sep037/구현/BOJ_1051.swift
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
저도 데미안이랑 비슷한 질문인데 작은 것부터 체크하신 이유가 있을까요?? 저는 문제보고 딱 큰거부터 체크 해야겠다고 생각이 들었거덩요.
제가 큰 거부터 찾은 이유는 문제에서 '가장 큰 정사각형'을 찾으라고 해서임요.(단순)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
헉 그런가요 ..! 저는 작은 것부터 찾아서 더 큰 게 없을 때까지 찾으려고 그냥 바로 생각이 들었는데 큰 것부터 가는 걸로도 한 번 풀어봐야겠서효

🔗 문제 링크
숫자 정사각형 🟨
하 발등에 불떨어져서 튀겨졌음니다
저도 스위프트로는 한 번도 안 풀어봐서 구현 문제 가져왔어요 ,, 늦어서 죄송하고요 ,, 어렵지 않은 녀석으로다가 대령합니다 ,,
✔️ 소요된 시간
30분 이내
✨ 수도 코드
가로로 먼저 같은 수가 있는지 찾고 그 길이만큼 세로로도 같으면 정사각형에 포함되는 숫자가 몇 개인지 (정사각형 넓이) 찾도록 함 !
1️⃣ 2차원 배열 입력받기
2️⃣ 모든 시작점(i, j)을 순회하면서
→ 이 위치를 정사각형의 왼쪽 위 꼭짓점이라고 가정
3️⃣ 가로로 같은 숫자가 나오는 길이만큼 확인
→ 오른쪽 끝 숫자랑 같은지 확인
4️⃣ 같은 길이만큼 세로로도 같은 숫자인지 확인
→ 아래쪽 끝, 대각선 끝 숫자 비교
5️⃣ 네 꼭짓점 숫자가 모두 같으면
→ (변 길이)^2 넓이를 계산해서 최댓값 갱신
6️⃣ 최댓값 출력
📚 새롭게 알게된 내용
.. ~
입력 형태가
3 5
42101
22100
22101
이런 식인데 첫 줄에 공백으로 구분도 안 하고 입력 받고,
두 번째 줄 입력 받을 때는 .separator("") 이렇게 하니까 컴파일 에러나서 뻿더니 돌아감 ^^!
📌 Swift의 split(separator:) 특징
split(separator: " ") 👉 공백 기준으로 분리 (정상)
split(separator: ",") 👉 쉼표 기준으로 분리 (정상)
❗️split(separator: "") 👉 이건 잘못된 방식 ! (삐빅)
얼른 문법을 다 알아야겠어요 안녕히 계세요