576. Out of Boundary Paths

https://leetcode.com/problems/out-of-boundary-paths/description/

http://www.cnblogs.com/grandyang/p/6927921.html

Solution:

思路:
使用一個三維的DP數組,其中dp[k][i][j]表示總共走k步,從(i,j)位置走出邊界的總路徑數。
遞推式:對于dp[k][i][j],走k步出邊界的總路徑數等于其周圍四個位置的走k-1步出邊界的總路徑數之和,如果周圍某個位置已經出邊界了,那么就直接加上1,否則就在dp數組中找出該值,這樣整個更新下來,我們就能得出每一個位置走任意步數的出界路徑數了,最后只要返回dp[N][i][j]就是所求結果了。

Time Complexity: O(mnN) Space Complexity: O(mn)

Solution Code:

public class Solution {
    public int findPaths(int m, int n, int N, int i, int j) {
        if (N <= 0) return 0;
        
        final int MOD = 1000000007;
        int[][] count = new int[m][n];
        count[i][j] = 1;
        int result = 0;
        
        int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        
        for (int step = 0; step < N; step++) {
            int[][] temp = new int[m][n];
            for (int r = 0; r < m; r++) {
                for (int c = 0; c < n; c++) {
                    for (int[] d : dirs) {
                        int nr = r + d[0];
                        int nc = c + d[1];
                        if (nr < 0 || nr >= m || nc < 0 || nc >= n) {
                            result = (result + count[r][c]) % MOD;
                        }
                        else {
                            temp[nr][nc] = (temp[nr][nc] + count[r][c]) % MOD;
                        }
                    }
                }
            }
            count = temp;
        }
        
        return result;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。