542. 01 Matrix

2025. 1. 7. 16:02·Algorithm/Leetcode

https://leetcode.com/problems/01-matrix/description/?envType=problem-list-v2&envId=breadth-first-search

 

 

 

 

Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
Output: [[0,0,0],[0,1,0],[1,2,1]]

 

1에서부터 가장 가까운 0의 값을 배열에 저장해주면 되는 문제였다.

 

  • 배열이 0이라면 큐에 삽입
    • 1이라면, -1로 초기화를 해준다 (거리 값 초기화)
  • 배열이 0인 곳에서부터 탐색을 하면서 거리가 -1인 곳을 계속해서 갱신해나가면 되는 문제였다. 

 

정답 코드

class Solution {
    int n, m;
    int [] dx = {1,0,-1,0};
    int [] dy = {0,1,0,-1};
    public int[][] updateMatrix(int[][] mat) {
        n = mat.length;
        m = mat[0].length;
        Queue<int []> q = new LinkedList<>();
        boolean [][] visited = new boolean[n][m];

        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if (mat[i][j] == 0) q.add(new int[]{i,j});
                else mat[i][j] = -1; // -1로 초기화 
            }
        }

        while(!q.isEmpty()) {
            int [] cur = q.poll();
            int x = cur[0];
            int y = cur[1];
            visited[x][y] = true;

            for(int dir = 0; dir < 4; dir++) {
                int nx = x + dx[dir];
                int ny = y + dy[dir];
                if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue;
                if (visited[nx][ny] || mat[nx][ny] == 0) continue;
                mat[nx][ny] = mat[x][y] + 1;
                visited[nx][ny] = true;
                q.add(new int[]{nx,ny});
            }
        }
        return mat;
    }
}

'Algorithm > Leetcode' 카테고리의 다른 글

3223. Minimum Length of String After Operations  (0) 2025.01.13
916. Word Subsets  (0) 2025.01.12
78. Subsets  (0) 2025.01.07
494. Target Sum  (2) 2025.01.06
1930. Unique Length-3 Palindromic Subsequences  (0) 2025.01.04
'Algorithm/Leetcode' 카테고리의 다른 글
  • 3223. Minimum Length of String After Operations
  • 916. Word Subsets
  • 78. Subsets
  • 494. Target Sum
미네구스
미네구스
  • 미네구스
    망구스 blog
    미네구스
  • 전체
    오늘
    어제
    • 분류 전체보기 (174)
      • Kotlin (0)
      • 시큐리티 (0)
        • 개발자 유미 (0)
      • 배포 (4)
      • 회고 (0)
      • Algorithm (143)
        • 프로그래머스 코딩테스트 문제풀이전략 (37)
        • 백준 (66)
        • 프로그래머스 (18)
        • Leetcode (22)
        • 코테 팁 (0)
      • 프로젝트 (8)
        • WEPIK (3)
        • PICK-O (5)
      • CS (1)
        • 운영체제 (5)
        • 네트워크 (1)
        • 면접스터디 (2)
      • 면접 (0)
        • 코테후기 (0)
        • 면접후기 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    백트래킹
    N과 M
    `
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
미네구스
542. 01 Matrix
상단으로

티스토리툴바