Untitled
unknown
java
6 months ago
2.0 kB
3
Indexable
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { static int[][] D = new int[101][101]; static int[][] board = new int[101][101]; static boolean [][] chk = new boolean[101][101]; static int N; static int M; static int[] dy = {0,0,1,-1}; static int[] dx = {1,-1,0,0}; static int INF = 130103330; public static void main(String[] args) throws IOException{ INPUT(); SOLVE(); // print(); } static void INPUT() throws IOException{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(bf.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); for(int i = 0;i<N;i++){ String nxt = bf.readLine(); int j =0; for(char c : nxt.toCharArray()){ board[i][j] = (c=='1') ? 1 : 0; D[i][j++] = INF; } } } static void print(){ for (int i = 0; i < N; i++) { for(int j = 0;j<M;j++){ // System.out.print(board[i][j] + " "); System.out.print(D[i][j] + " "); } System.out.println(); } } static void SOLVE(){ D[0][0] = 1; DFS(0,0); System.out.println(D[N-1][M-1]); } static void DFS(int y, int x){ if(isOutside(y, x) || board[y][x]==0){ return; } for(int i = 0;i<4;i++){ int ny = y + dy[i]; int nx = x + dx[i]; if(isOutside(ny, nx)) continue; if(board[ny][nx] == 1 && D[ny][nx]>D[y][x]+1){ // System.out.println(ny +" " + nx); D[ny][nx] = D[y][x] + 1; DFS(ny, nx); } } } static boolean isOutside(int ny, int nx){ return (0>ny || ny>=N || 0>nx || nx>=M); } }
Editor is loading...
Leave a Comment