【算法設計】- 機器人的運動范圍
算法分析
機器人的運動范圍
● ○ ●
The range of motion of the robot
● ○ ●
??????????
題目描述
地上有一個 m 行和 n 列的方格。一個機器人從坐標 (0, 0) 的格子開始移動,每一次只能向左右上下四個方向移動一格,但是不能進入行坐標和列坐標的數(shù)位之和大于 k 的格子。
例如,當 k 為 18 時,機器人能夠進入方格 (35,37),因為 3+5+3+7=18。但是,它不能進入方格 (35,38),因為 3+5+3+8=19。請問該機器人能夠達到多少個格子?

解題思路
使用深度優(yōu)先搜索(Depth First Search,DFS)方法進行求解?;厮菔巧疃葍?yōu)先搜索的一種特例,它在一次搜索過程中需要設置一些本次搜索過程的局部狀態(tài),并在本次搜索結束之后清除狀態(tài)。而普通的深度優(yōu)先搜索并不需要使用這些局部狀態(tài),雖然還是有可能設置一些全局狀態(tài)。
private static final int[][] next = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};private int cnt = 0;private int rows;private int cols;private int threshold;private int[][] digitSum;public int movingCount(int threshold, int rows, int cols) {this.rows = rows;this.cols = cols;this.threshold = threshold;initDigitSum();boolean[][] marked = new boolean[rows][cols];dfs(marked, 0, 0);return cnt;}private void dfs(boolean[][] marked, int r, int c) {if (r < 0 || r >= rows || c < 0 || c >= cols || marked[r][c])return;marked[r][c] = true;if (this.digitSum[r][c] > this.threshold)return;cnt++;for (int[] n : next)dfs(marked, r + n[0], c + n[1]);}private void initDigitSum() {int[] digitSumOne = new int[Math.max(rows, cols)];for (int i = 0; i < digitSumOne.length; i++) {int n = i;while (n > 0) {digitSumOne[i] += n % 10;n /= 10;}}this.digitSum = new int[rows][cols];for (int i = 0; i < this.rows; i++)for (int j = 0; j < this.cols; j++)this.digitSum[i][j] = digitSumOne[i] + digitSumOne[j];}

?????????
「?? 感謝大家」
如果你覺得這篇內(nèi)容對你挺有有幫助的話:
點贊支持下吧,讓更多的人也能看到這篇內(nèi)容(收藏不點贊,都是耍流氓 -_-) 歡迎在留言區(qū)與我分享你的想法,也歡迎你在留言區(qū)記錄你的思考過程。 覺得不錯的話,也可以閱讀近期梳理的文章(感謝各位的鼓勵與支持??????): 計算機下SSL安全網(wǎng)絡通信(420+??) 夢魘回生的博客:https://gain-wyj.cn/(680+??) 【震驚】手把手教你用python做繪圖工具(580+??) 【算法分析】——快速冪算法(160+??) 數(shù)據(jù)可視化:利用Python和Echarts制作“用戶消費行為分析”可視化大屏??????(210+??) 手把手教你進行pip換源(230+??) 用python實現(xiàn)前向分詞最大匹配算法(220+??) 教你用python操作攝像頭以及對視頻流的處理(240+??) 匯總超全的Matplotlib可視化最有價值的 50 個圖表(附完整 Python 源代碼)(一)(240+??) 小程序云開發(fā)項目的創(chuàng)建與配置(240+??)

發(fā)現(xiàn)更多精彩
關注公眾號


點分享

點點贊

點在看

評論
圖片
表情
