문제 : https://www.acmicpc.net/problem/2178


import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = Integer.parseInt(scan.next());
        int m = Integer.parseInt(scan.next());
        
        
        Queue q = new LinkedList();
        Node[][] arr = new Node[n][m];

        for(int i = 0 ; i < n ; i++) {
            String row = scan.next();
            for(int j = 0 ; j < m ; j++) {
                arr[i][j] = new Node(i,j,row.charAt(j) - '0');
            }
        }

        q.offer(arr[0][0]);
        //입력부
        
        while(!q.isEmpty()) {
            Node node = q.poll();
//            System.out.println(node);
            Node[] ajNode = find(node,n,m,arr) ;
//            //이동가능한 노드를 찾는다
            for(int i =0 ; i < 4 ; i++) {
                if(ajNode[i] != null) {
                    ajNode[i].value=-1;
                    //큐에 넣는다
                    q.offer(ajNode[i] );
                }
                
            }
        }
        scan.close();
        System.out.println(arr[n-1][m-1].dist);
    }
//    
    static Node[] find(Node node,int col, int row ,Node[][] array) {
        Node[] result = new Node[4];
        int addC[] = {0,0,-1,1};
        int addR[] = {-1,1,0,0};
        
        for(int i = 0 ; i < 4 ; i ++) {
            
            int c = node.col+addC[i];
            int r = node.row+addR[i];
            
            if(c >= col || r >= row || c < 0 || r < 0 ) {
                result[i] = null;
            }else {
                if(array[c][r].value == 1 ) {
                    array[c][r].dist = node.dist+1;
                    result[i] = array[c][r];
//                    System.out.println("삽입예정 노드" + result[i]);
                }else {
                    result[i] = null;
                }
            }
        }
        return result;
    }

    static class Node {
        int row ;
        int col ; 
        int value;
        int dist = 1;
        
        public Node(int col,int row, int value) {
            this.row = row;
            this.col = col;
            this.value = value;
        }

        @Override
        public String toString() {
            return "Node [row=" + row + ", col=" + col + ", value=" + value + "]";
        }
    }
}

+ Recent posts

"여기"를 클릭하면 광고 제거.