ロボット66の移動範囲

タイトル説明

接地グリッドと、m行n列。0,0グリッド座標からロボットが移動し、毎回四方セルを上下、左右が、グリッドの行および列の座標を入力することができないだけではビットkの数の合計よりも大きいです。kが18である場合、例えば、ロボットが3 + 3 + 5 + 7 = 18から、ボックス(35、37)を入力することができます。3 + 3 + 5 + 8 = 19しかし、それは、ボックス(35、38)を入力することができません。ロボットは、格子の数に到達することができるだろうか?

アイデア解析

この質問と同じ、バックトラック/感染の前に質問。タグの配列は、ビットの行および列の座標をカウントすることにより、関数番号で計算したグローバル変数の数を、この位置を通過していないと。終了条件は、範囲外の添字、この位置を介して、閾値よりも桁大きいです。

コードの実装

    public int count = 0;

    public int movingCount(int threshold, int rows, int cols) {
        if (rows == 0 || cols == 0) {
            return -1;
        }
        int[][] matrix = new int[rows][cols];
        process(threshold, rows, cols, 0, 0, matrix);
        return count;
    }

    public void process(int threshold, int rows, int cols, int row, int col, int[][] matrix) {
        int bitSum = countBit(row, col);
        if (row < 0 || col < 0 || row >= rows || col >= cols || bitSum > threshold || matrix[row][col] == 1) {
            return;
        }
        count++;
        matrix[row][col] = 1;
        process(threshold, rows, cols, row - 1, col, matrix);
        process(threshold, rows, cols, row + 1, col, matrix);
        process(threshold, rows, cols, row, col - 1, matrix);
        process(threshold, rows, cols, row, col + 1, matrix);
    }

    public int countBit(int row, int col) {
        int sum = 0;
        while (row != 0) {
            sum += row % 10;
            row = row / 10;
        }
        while (col != 0) {
            sum += col % 10;
            col = col / 10;
        }
        return sum;
    }
公開された117元の記事 ウォンの賞賛8 ビュー3713

おすすめ

転載: blog.csdn.net/qq_34761012/article/details/104480742
おすすめ