资讯动态

LeetCode //C - 1301. Number of Paths with Max Score

发布时间:2026/10/24 2:04:06 来源:尧图企业网站定制
1301. Number of Paths with Max ScoreYou are given a square board of characters. You can move on the board starting at the bottom right square marked with the character ‘S’.You need to reach the top left square marked with the character ‘E’. The rest of the squares are labeled either with a numeric character 1, 2, …, 9 or with an obstacle ‘X’. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 7.In case there is no path, return [0, 0].Example 1:Input:board [“E23”,“2X2”,“12S”]Output:[7,1]Example 2:Input:board [“E12”,“1X1”,“21S”]Output:[4,2]Example 3:Input:board [“E11”,“XXX”,“11S”]Output:[0,0]Constraints:2 board.length board[i].length 100From: LeetCodeLink: 1301. Number of Paths with Max ScoreSolution:Ideas:Use dynamic programming to store the maximum score and number of maximum-score paths reaching each cell.Code:#includestdlib.h#includestring.h#defineMOD1000000007/** * Note: The returned array must be malloced, assume caller calls free(). */int*pathsWithMaxScore(char**board,intboardSize,int*returnSize){intmaxScore[100][100];intpathCount[100][100];for(inti0;iboardSize;i){for(intj0;jboardSize;j){maxScore[i][j]-1;pathCount[i][j]0;}}maxScore[0][0]0;pathCount[0][0]1;for(inti0;iboardSize;i){for(intj0;jboardSize;j){if(board[i][j]X||(i0j0)){continue;}intbest-1;longlongways0;/* Cell above */if(i0maxScore[i-1][j]best){bestmaxScore[i-1][j];wayspathCount[i-1][j];}elseif(i0maxScore[i-1][j]bestbest!-1){wayspathCount[i-1][j];}/* Cell to the left */if(j0maxScore[i][j-1]best){bestmaxScore[i][j-1];wayspathCount[i][j-1];}elseif(j0maxScore[i][j-1]bestbest!-1){wayspathCount[i][j-1];}/* Upper-left diagonal cell */if(i0j0maxScore[i-1][j-1]best){bestmaxScore[i-1][j-1];wayspathCount[i-1][j-1];}elseif(i0j0maxScore[i-1][j-1]bestbest!-1){wayspathCount[i-1][j-1];}if(best-1){continue;}intvalue0;if(board[i][j]1board[i][j]9){valueboard[i][j]-0;}maxScore[i][j]bestvalue;pathCount[i][j]ways%MOD;}}int*result(int*)malloc(2*sizeof(int));*returnSize2;if(maxScore[boardSize-1][boardSize-1]-1){result[0]0;result[1]0;}else{result[0]maxScore[boardSize-1][boardSize-1];result[1]pathCount[boardSize-1][boardSize-1];}returnresult;}

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑