【LeetCode】面试题13. 机器人的运动范围(JAVA)

原题地址:https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/

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

示例 1:
输入:m = 2, n = 3, k = 1
输出:3

示例 1:
输入:m = 3, n = 1, k = 0
输出:1

提示:
1 <= n,m <= 100
0 <= k <= 20

解题方案:
可以用DFS和BFS进行遍历,要注意的是遍历的过程只会往右下方走,所有左上不需要考虑。

代码:
DFS(100%)

class Solution {
    int m;
    int n;
    int k;
    int count;
    int[][] visited;
    public int movingCount(int m, int n, int k) {
        if(m == 0 || n == 0) return 0;
        visited = new int[m][n];
        this.m = m;
        this.n = n;
        this.k = k;
        count = 0;
        DFS(0, 0);
        return count;
    }

    public void DFS(int i, int j)
    {
        if(i < 0 || i >= m || j < 0 || j >= n || visited[i][j] == 1) return;
        int x = i, y = j;
        int sum = 0;
        while(x != 0){sum += x % 10; x /= 10;}
        while(y != 0){sum += y % 10; y /= 10;}
        if(sum <= k)
        {
            visited[i][j] = 1;
            count ++;
        }
        else
            return;
        DFS(i + 1, j);
        DFS(i, j + 1);
    }

}

BFS

class Solution {
    public int movingCount(int m, int n, int k) {
        if(m == 0 || n == 0) return 0;
        Queue<Integer> q = new LinkedList<>();
        int[][] visited = new int[m][n];
        q.add(0); q.add(0);
        visited[0][0] = 1;
        int count = 0;
        int i, j;
        while(!q.isEmpty())
        {
            i = q.remove();
            j = q.remove();
            count ++;

            if(i + 1 < m && visited[i + 1][j] == 0)
            {
                int sum = 0;
                int x = i + 1, y = j;
                while(x != 0){ sum += x % 10; x /= 10;}
                while(y != 0){ sum += y % 10; y /= 10;}
                if(sum <= k)
                {
                    q.add(i + 1); q.add(j);
                    visited[i + 1][j] = 1;
                }
            }
            if(j + 1 < n && visited[i][j + 1] == 0)
            {
                int sum = 0;
                int x = i, y = j + 1;
                while(x != 0){ sum += x % 10; x /= 10;}
                while(y != 0){ sum += y % 10; y /= 10;}
                if(sum <= k)
                {
                    q.add(i); q.add(j + 1);
                    visited[i][j + 1] = 1;
                }
            }
        }
        return count;
    }
}
发布了110 篇原创文章 · 获赞 4 · 访问量 9330

猜你喜欢

转载自blog.csdn.net/rabbitsockx/article/details/104384850
今日推荐