题解 | #拜访#

拜访

https://www.nowcoder.com/practice/491828fc7d93459db450b344c2aaaeef?tpId=196&tqId=39667&rp=1&ru=/exam/oj&qru=/exam/oj&sourceUrl=%2Fexam%2Foj%3Ftab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D196%26judgeStatus%3D3&difficulty=undefined&judgeStatus=3&tags=&title=

import java.util.*;


public class Solution {
    
    /**********************************************************************************/
    public int shortestDistance;
    public int methodNumber = 0;
    public int rows;
    public int columns;

    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param CityMap int整型二维数组
     * @param n       int整型
     * @param m       int整型
     * @return int整型
     */
    public int countPath(int[][] CityMap, int n, int m) {
        // write code here
        rows = n;
        columns = m;
        shortestDistance = n * m;
        int[] ManagerLocation = findManagerLocation(CityMap);
        process(ManagerLocation[0], ManagerLocation[1], CityMap, 0);
        return methodNumber;
    }

    public int[] findManagerLocation(int[][] CityMap) {
        int[] ManagerLocation = new int[2];
        for (int currentX = 0; currentX < rows; currentX++) {
            for (int currentY = 0; currentY < columns; currentY++) {
                if (CityMap[currentX][currentY] == 1) {
                    ManagerLocation[0] = currentX;
                    ManagerLocation[1] = currentY;
                    break;
                }
            }
        }
        return ManagerLocation;
    }

    public void process(int currentX, int currentY, int[][] CityMap, int haveTakenSteps) {
        if (currentX < 0 || currentX >= rows || currentY < 0 || currentY >= columns || CityMap[currentX][currentY] == -1) {
            return;
        }
        if (CityMap[currentX][currentY] == 2) {
            if (haveTakenSteps == shortestDistance) {
                methodNumber++;
            } else if (haveTakenSteps < shortestDistance) {
                shortestDistance = haveTakenSteps;
                methodNumber = 1;
            }
            return;
        }
        CityMap[currentX][currentY] = -1;
        process(currentX - 1, currentY, CityMap, haveTakenSteps + 1);
        process(currentX + 1, currentY, CityMap, haveTakenSteps + 1);
        process(currentX, currentY - 1, CityMap, haveTakenSteps + 1);
        process(currentX, currentY + 1, CityMap, haveTakenSteps + 1);
        CityMap[currentX][currentY] = 0;
    }
}
全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务