這次的題目是個九宮格小遊戲,透過二維陣列橫縱列來解題,陣列裡面0代表的就是鬼屋,要避免住到鬼屋以及鬼屋下面,所以要從colum欄 row列一一去算,如遇到了就要跳過,並將其餘可住的數值都加總起來,答案就解開了。所以帶大家看看簡單的二維陣列怎麼解,怎麼寫可以取想取的數值,就一起來看看吧!
題目
After becoming famous, the CodeBots decided to move into a new building together. Each of the rooms has a different cost, and some of them are free, but there's a rumour that all the free rooms are haunted! Since the CodeBots are quite superstitious, they refuse to stay in any of the free rooms, or any of the rooms below any of the free rooms.
Given matrix, a rectangular matrix of integers, where each value represents the cost of the room, your task is to return the total sum of all rooms that are suitable for the CodeBots (ie: add up all the values that don't appear below a 0).
範例
Input/Output
- [execution time limit] 4 seconds (js)
- [input] array.array.integer matrixA 2-dimensional array of integers representing the cost of each room in the building. A value of 0 indicates that the room is haunted.Guaranteed constraints:
1 ≤ matrix.length ≤ 5,
1 ≤ matrix[i].length ≤ 5,
0 ≤ matrix[i][j] ≤ 10.
- [output] integerThe total price of all the rooms that are suitable for the CodeBots to live in.
解題
function solution(matrix) {
let rowLength = matrix.length;
let ghost=[];
let ans=0;
if(rowLength>0){
let columLength = matrix[0].length;
for(let i = 0; i < rowLength; i++){
for(let j = 0; j < columLength; j++){
if(!ghost.includes(j)){
if(matrix[i][j]===0){
ghost.push(j);
}else{
ans +=matrix[i][j];
}}}}}
return ans;
}
想法
先宣告rowLength列為一維陣列的長度,以及ghost為鬼屋處,以及答案值ans
並進行兩次迴圈判斷,收先如果rowLength數組的長度大於0,那就開啟以下條件,讓columLength欄等於總欄位長度,設定外層迴圈為i內圈迴圈為j,外層會透過迴圈去跑每個列,內圈則是透過迴圈去每個欄。
如果鬼屋不包含某欄中,又如果matrix[i][j]某列中的某欄值為0,那就將它塞進鬼屋Array陣列當中。否則,就將剩下的的數值都加總起來,其數值等於答案ans。
由於是刷題練習比較嚴格,要注意跑雙迴圈時,跑的時間有沒有超過題目限制的時間,如果跑太久超過了,那也會被判斷是錯誤喔!
歡迎大家留言互相交流~