機器人的運動范圍

《劍指offer》面試題13:矩陣中的路徑

題目:地上有一個m行和n列的方格。一個機器人從坐標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行坐標和列坐標的數(shù)位之和大于k的格子。 例如,當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。但是,它不能進入方格(35,38),因為3+5+3+8 = 19。請問該機器人能夠達到多少個格子?

思路:回溯法:核心思路:
1.從(0,0)開始走,每成功走一步標記當前位置為true,然后從當前位置往四個方向探索,
返回1 + 4 個方向的探索值之和。
2.探索時,判斷當前節(jié)點是否可達的標準為:
1)當前節(jié)點在矩陣內(nèi);
2)當前節(jié)點未被訪問過;
3)當前節(jié)點滿足check(行坐標和列坐標的數(shù)位之和小于等于k)限制。

代碼如下:

public int movingCount(int threshold,int rows,int cols) {
    boolean[] visited = new boolean[rows*cols];
    return movingCountCore(threshold,rows,cols,0,0,visited);
}

private int movingCountCore(int threshold,int rows,int cols,int row,int col,boolean[] visited) {
    int count = 0;
    if (row >= 0 && row < rows && col >= 0 && col < cols && !visited[row * cols + col] && check(threshold,row,col)) {
        visited[row * cols + col] = true;
        count = 1 + movingCountCore(threshold,rows,cols,row + 1,col,visited) // 下
                + movingCountCore(threshold,rows,cols,row - 1,col,visited) // 上
                + movingCountCore(threshold,rows,cols,row,col + 1,visited) // 右
                + movingCountCore(threshold,rows,cols,row,col - 1,visited); // 左
    }
    return count;
}

private boolean check(int threshold,int row,int col) {
    int sum = 0;
    while (row != 0) {
        sum += sum%row;
        row = row/10;
    }
    while (col != 0) {
        sum += sum%col;
        col = col/10;
    }
    if (sum > threshold) {
        return false;
    }
    return true;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容