剑指offer——(33)机器人的运动范围

剑指offer——(33)机器人的运动范围_第1张图片

注意格子中的值应该是行坐标和列坐标的数位之和!

public class Solution {
     
    int shang[][];
    int dx[] = new int[]{
     -1, 1, 0, 0}; // 水平方向
    int dy[] = new int[]{
     0, 0, -1, 1}; // 竖直方向
    int result = 0;
    boolean[][] TOF;

    public int movingCount(int threshold, int rows, int cols) {
     
        if(rows==1&&cols==1){
     
            if(threshold>=0) return 1;
            else return 0;
        }
        shang = new int[rows][cols];
        for (int i = 0; i < rows; i++) {
     
            for (int j = 0; j < cols; j++) {
     
                String s = String.valueOf(i)+String.valueOf(j);
                shang[i][j] = location(s, s.length());
            }
        }
        TOF = new boolean[rows][cols];
        search(0, 0, rows, cols, threshold);
        return result;
    }
    /**
     * 填充方格数值 行坐标和列坐标的数位之和
     * @param s
     * @param length
     * @return
     */
   int location(String s, int length){
     
        int local = 0;
        for(int i=0;i<length;i++){
     
            local += Integer.parseInt(String.valueOf(s.charAt(i)));
        }
        return local;
    }

    void search(int x, int y, int rows, int cols, int threshold) {
     
    	// 向左,右,上,下
        for (int i = 0; i < 4; i++) {
     
            int xx = x + dx[i];
            int yy = y + dy[i];
            if (xx >= 0 && xx < rows && yy >= 0 && yy < cols && shang[xx][yy] <= threshold && TOF[xx][yy] == false) {
     
                result++;
                if (xx == rows && yy == cols) {
     
                    return;
                }
                TOF[xx][yy] = true;
                search(xx, yy, rows, cols, threshold);
            }
        }
    }

    public static void main(String[] args) {
     
        // TODO Auto-generated method stub
        System.out.println(new Solution().movingCount(15,1,1)); 
    }

}

你可能感兴趣的:(Java,牛客网,剑指offer,数据结构/算法,机器人的运动范围,牛客网,剑指offer)