穿越雷區

/*標題:穿越雷區   X星的坦克戰車很奇怪,它必須交替地穿越正能量輻射區和負能量輻射區才能保持正常運轉,不然將報廢。 

某坦克須要從A區到B區去(A,B區自己是安全區,沒有正能量或負能量特徵),怎樣走才能路徑最短?   已知的地圖是一個方陣,上面用字母標出了A,B區,
其它區都標了正號或負號分別表示正負能量輻射區。 例如: A + - + - - + - - + - + + + - + - + - + B + - + -   坦克車只能水平或垂直方向上移
動到相鄰的區。   數據格式要求:   輸入第一行是一個整數n,表示方陣的大小, 4<=n<100  接下來是n行,每行有n個數據,多是A,B,+,-中的某一個,
中間用空格分開。 A,B都只出現一次。   要求輸出一個整數,表示坦克從A區到B區的最少移動步數。 
若是沒有方案,則輸出-1   
例如: 用戶輸入: 
5  
A + - + -
- + - - + 
- + + + - 
+ - + - + 
B + - + -   
   則程序應該輸出: 10   
資源約定:  峯值內存消耗(含虛擬機) < 512M CPU消耗  < 2000ms    請嚴格按要求輸出,不要多此一舉地打印相似:「請您輸入...」 的多餘內容。   
全部代碼放在同一個源文件中,調試經過後,拷貝提交該源碼。 注意:不要使用package語句。不要使用jdk1.7及以上版本的特性。*/
package test;

import java.util.Scanner;

public class 穿越雷區 {
    static String[][] a;
    static int n;
    static boolean vis[][];
    static int min=Integer.MAX_VALUE;
    static int[][] path={{0,1},{0,-1},{-1,0},{1,0}};
    public static void main(String arg[])
    {
        Scanner input=new Scanner(System.in);
        n=input.nextInt();
        input.nextLine();
        a=new String[n][n];
        vis=new boolean[n][n];
        vis[0][0]=true;
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++)
            {
                a[i][j]=input.next();
            }
        }
        /*for(int i=0;i<n;i++){
            for(int j=0;j<n;j++)
            {
                System.out.print(a[i][j]);
            }
            System.out.println();
        }*/
        dfs(0,0,0);
        System.out.println(min);
    }
    private static void dfs(int x, int y,int step) {
        // TODO Auto-generated method stub
        if(a[x][y].equals("B"))
        {
            //System.out.println(step);
            if(step<min)
                min=step;
        }
        for(int i=0;i<4;i++)
        {
            int tempx=x+path[i][0];
            int tempy=y+path[i][1];
            if(tempx>=0&&tempx<n&&tempy>=0&&tempy<n){
            if(vis[tempx][tempy]==false&&!a[x][y].equals(a[tempx][tempy]))
            {
                vis[tempx][tempy]=true;
                dfs(tempx,tempy,step+1);
                vis[tempx][tempy]=false;
            }
            }
        }
    }

}
相關文章
相關標籤/搜索