on
Java 토마토
Java 토마토
final static int[] xArray = {1, 0, -1, 0}; final static int[] yArray = {0, 1, 0, -1}; public static class Node { int x; int y; public Node(int x, int y) { this.x = x; this.y = y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public int getX() { return this.x; } public int getY() { return this.y; } } public static void main(String[] args) { tomato(); } private static void tomato() { int arrayLength = xArray.length; int board[][] = { { 0, 0, 0, 0, 0, 0 }, { 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1 }, }; int n = board.length; int m = board[0].length; int[][] dist = new int[n][m]; Queue queue = new LinkedList<>(); for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(board[i][j] == 1) { queue.add(new Node(i, j)); } dist[i][j] = board[i][j]; } } while (!queue.isEmpty()) { Node node = queue.poll(); for(int i = 0; i < arrayLength; i++) { int x = node.getX() + xArray[i]; int y = node.getY() + yArray[i]; if(x < 0 || x >= n || y < 0 || y >= m) { continue; } if(board[x][y] == -1) { continue; } if(dist[x][y] >= 1) { continue; } dist[x][y] = dist[node.getX()][node.getY()] + 1; queue.add(new Node(x, y)); } } int ans = 0; for (int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(dist[i][j] > ans) { ans = dist[i][j]; } } } System.out.println(ans); }
공유하기 글 요소 저작자표시
from http://nahyungmin.tistory.com/275 by ccl(A) rewrite - 2021-12-20 17:27:25