度小满0920

多组数据,第1行有1个正整数T,表示有T组数据。(T<=100)

对于每组数据,第1行有两个整数N和M。(1<=N, M<=1000)

接着N行,每行有一个长度为M的字符串,表示N*M的迷宫。
输出一个整数,表示使用特异功能的最少次数。如果小昆虫不能走出迷宫,则输出-1。
假设小昆虫在一个N*M的迷宫中,"@"代表小昆虫的初始位置,"."代表可以通过的空地,"*"代表可以破坏的障碍物,
"#"代表不可破坏的障碍物。请问小昆虫最少需要使用多少次特异功能才可以逃出迷宫?
3
3 3
###
#@*
***
3 4
####
#@.*
**.*
3 3
.#.
#@#
.#.
public class Main02 {
    public static int[] findStartPos(char[][] grid, int n, int m) {
        for(int i=0; i < n; i++) {
            for(int j=0; j < m; j++) {
                if(grid[i][j] == '@')
                    return new int[]{i,j};
            }
        }
        return new int[] {};
    }
    static int[] dx = new int[] {0,0,1,-1};
    static int[] dy = new int[] {1,-1,0,0};
    static boolean[][] used ;
    static int result ;
    public static void solve(char[][] grid, int n, int m, int x, int y, int res) {
        if(x < 0 || x >= n || y < 0 || y >= m) {
            //System.out.println(Arrays.deepToString(used));
            result = Math.min(res, result);
            return ;
        }
        if(grid[x][y] == '#' || used[x][y] == true) return ;
        if(grid[x][y] == '*') res++;
        used[x][y] = true;
        for(int i=0; i < 4; i++) {
            int xx = x + dx[i], yy = y + dy[i];
            solve(grid, n, m, xx, yy, res);
        }
        used[x][y] = false;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int times = sc.nextInt();
        while(times-- > 0) {
            int n = sc.nextInt(), m = sc.nextInt();
            char[][] grid = new char[n][m];
            for(int i=0; i < n; i++)
                grid[i] = sc.next().toCharArray();
            int[] xy = findStartPos(grid, n,m);
            used = new boolean[n][m];
            result = Integer.MAX_VALUE;
            int x= xy[0], y = xy[1];
            solve(grid,n,m,x,y,0);
            if(result == Integer.MAX_VALUE) {
                System.out.println(-1);
            }else{
                System.out.println(result);
            }
        }
    }

}

回溯一定别忘了跳出循环!!!!!!!!!!!!!!!!!!!!!

public class Main01 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        char[] a = sc.next().toCharArray();
        char[] b = sc.next().toCharArray();
        int[] cntA = new int[26];
        int[] cntB = new int[26];
        for(int i=0; i < a.length; i++)
            cntA[a[i]-'A'] ++;
        for(int i=0; i < b.length; i++)
            cntB[b[i]-'A'] ++;
        //System.out.println(Arrays.toString(cntA));
        int res = 0;
        for(int i=0; i < 26; i++)
            res += Math.min(cntA[i],cntB[i]);
        System.out.println(res);
    }
}
原文地址:https://www.cnblogs.com/lixyuan/p/13702772.html