机器人的运动范围 java

版权声明:转载表明出处即可 @_@ https://blog.csdn.net/Cai_Nia/article/details/90765557

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

import java.util.LinkedList;
public class Solution {
    public int movingCount(int threshold, int rows, int cols)
    {
        if (threshold < 0) {
            return 0;
        }
        boolean[][] tag = new boolean[rows][cols];
        LinkedList<Node21> nodeList = new LinkedList<>();
        Node21 node = new Node21(0, 0);
        nodeList.push(node);
        int sum = 1;
        tag[0][0] = true;
        while (!nodeList.isEmpty()) {
            Node21 nowNode = nodeList.pop();
            int[] dx = {1, -1, 0, 0};
            int[] dy = {0, 0, 1, -1};
            for (int i = 0; i < 4; ++i) {
                Node21 tempNode = new Node21(nowNode.x + dx[i], nowNode.y + dy[i]);
                if (judge(tempNode, tag, threshold)) {
                    ++sum;
                    nodeList.push(tempNode);
                }
            }
        }
        return sum;
    }
    public boolean judge(Node21 tempNode, boolean[][] tag, int limitSum) {
        int sum = 0, tempX = tempNode.x, tempY = tempNode.y;
        while (tempX != 0) {
            sum = sum + tempX % 10;
            tempX = tempX / 10;
        }
        while (tempY != 0) {
            sum = sum + tempY % 10;
            tempY = tempY / 10;
        }
        if (sum <= limitSum) {
            if (tempNode.x < 0 || tempNode.x >= tag.length || tempNode.y < 0 || tempNode.y >= tag[0].length) {
                return false;
            }
            if (tag[tempNode.x][tempNode.y] == false) {
                tag[tempNode.x][tempNode.y] = true;
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }

    }
}
class Node21 {
    int x, y;
    public Node21(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

 

展开阅读全文

没有更多推荐了,返回首页