-
행렬_LeetCode_542 01matrix알고리즘/알고리즘 문제풀이 2022. 1. 24. 17:03
https://leetcode.com/problems/01-matrix/
오답
testCase 49/50에서 막힌다.
정말 획기적인 방법을 사용하지 않는이상 통과가 힘든듯 ㅠㅠㅠ
더보기더보기func updateMatrix(_ mat: [[Int]]) -> [[Int]] { var sol = [[Int]].init(repeating: [Int].init(repeating: -1, count: mat[0].count), count: mat.count) var queue = [[Int]]() let emptyRow = [Bool].init(repeating: false, count: mat[0].count) var visited = [[Bool]].init(repeating: emptyRow, count: mat.count) let columnLimit = mat[0].count let rowLimit = mat.count for (row,i) in mat.enumerated() { for (column,j) in i.enumerated(){ if j == 0 { sol[row][column] = 0 } else { for rep in 0..<visited.count { visited[rep] = emptyRow } visited[row][column] = true let moves = [[-1, 0], [1, 0], [0, 1], [0, -1]] queue.append([row,column,0]) while queue.isEmpty != true { let now = queue.removeFirst() let tempRow = now[0] let tempColumn = now[1] let tempCount = now[2] for move in moves { let nextRow = tempRow + move[0] let nextColumn = tempColumn + move[1] let nextCount = tempCount + 1 if nextRow >= rowLimit || nextColumn >= columnLimit || nextRow < 0 || nextColumn < 0 { // print("move: \(move), now: \(now)", // "row : \(tempRow + move[0]), rowLimit: \(rowLimit)", // "column : \(tempColumn + move[1]), columnLimit: \(columnLimit)") continue } if visited[nextRow][nextColumn] { continue } // print("log: now:\(now), next: \([nextRow,nextColumn,nextCount])") if mat[nextRow][nextColumn] == 0 { sol[row][column] = nextCount queue.removeAll() // print("if: true, \([nextRow,nextColumn,nextCount]), mat[nextRow][nextColumn]: \(mat[nextRow][nextColumn])") break } else { visited[nextRow][nextColumn] = true queue.append([nextRow,nextColumn,nextCount]) // print("if: false, \([nextRow,nextColumn,nextCount]), mat[nextRow][nextColumn]: \(mat[nextRow][nextColumn])") } } } } } } return sol }
'알고리즘 > 알고리즘 문제풀이' 카테고리의 다른 글
행렬_Leetcode_130.Surrounded Region Swift (0) 2022.01.25 행렬_백준_1012 (0) 2022.01.25 ?_백준_2606 swift (0) 2022.01.18 문자열, 재귀_백준_2800 swift (0) 2022.01.18 재귀, 문자열_카카오기출_프로그래머스_괄호 변환 swift (0) 2021.12.28