编辑代码

import java.util.Scanner;
import java.util.*;
// 1:无需package
// 2: 类名必须Main, 不可修改

public class Main {
  static int m = 30;
  static int n = 50;
  static int[][] state;
  static int ans = Integer.MAX_VALUE;
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int count = 0;
        String s = "";
        state = new int[30][50];
        char[][] grid = new char[30][50];
        for(int i = 0;i<30;i++)
        {
            String a = scan.nextLine();
            s = s+a;
        }
        for(int i = 0;i<30;i++)
        {
            for(int j = 0;j<50;j++)
            {
                grid[i][j] = s.charAt(count);
                count++;
            }
        }
        dfs(0,0,grid,0);

        scan.close();
        System.out.println(ans);
    }
    public static void dfs(int x,int y,char[][] mat,int step)
    {
        if(x<0||x>=30||y<0||y>=50||state[x][y]==1||mat[x][y]=='1')
        {
            return;
        }
        state[x][y] = 1;
        if(x-1>=0&&state[x-1][y]==0&&mat[x-1][y]=='0')
        {
            dfs(x-1,y,mat,step+1);
        }
        if(x+1<m&&state[x+1][y]==0&&mat[x+1][y]=='0')
        {
            dfs(x+1,y,mat,step+1);
        }
        if(y-1>=0&&state[x][y-1]==0&&mat[x][y-1]=='0')
        {
            dfs(x,y-1,mat,step+1);
        }
        if(y+1<n&&state[x][y+1]==0&&mat[x][y+1]=='0')
        {
            dfs(x,y+1,mat,step+1);
        }
        state[x][y] = 0;
        if(x==29&&y==49)
        {
            ans = Math.min(ans,step);
        }
    }
}