Huawei Machine Test-all roads to Rome

Source: Internet
Author: User

Topic:



Basic idea:

This is a deep search problem, however, you can see the answer to the question: the number of cities, so can not use a full traversal, can not meet the complexity of time requirements. So the data needs to be preprocessed, that is, to convert the map into a linked list, the map should be only 0, 1 of the value, indicating that there is a path or no path. However, in order to save some memory (although not necessary), so map multiplexing. If the current node I is connected to another node J, the node J is placed in the map. The No. 0 element holds the current access to the first node (starting from 1, which is useful when searching backwards), followed by a node adjacent to it, and finally ending with-1.


Code:

#include <stdio.h> #include <string.h>int main () {const int N = 10;int map[n][n];int stack[n];bool visited[n];  int N,a,b;int begin;int i,j;while (scanf ("%d%d%d", &n, &a, &b)! = EOF) {for (i = 0; i < n; ++i) {for (j = 0; j < n; ++J) {scanf ("%d", &map[i][j]);}} for (i = 0; i < n; ++i) {int index = 0;map[i][0] = 1;for (j = 0; J < N; ++j) {if (Map[i][j] && i! = j) Map[i][++in DEX] = j;//record the point}map[i][++index] = -1;//-1 end}//Deep Search memset (visited, 0, N * sizeof (BOOL)); int top = -1;int ans = 0;stack[++t OP] = a;//a into stack visited[a] = true;while (Top >-1)//Stack not empty {Begin = stack[top];//take stack top element for (i = map[begin][0]; Map[begin][i]! =- 1; ++i) {if (map[begin][i]! = b &&!visited[map[begin][i]])//not visited {Stack[++top] = Map[begin][i];visited[map[begin] [i]] = true;map[begin][0] = i + 1;break;} if (map[begin][i] = = b) ++ans;} if (map[begin][i] = = 1)//The point of all the paths have gone through, the stack {--top;}} End for whileprintf ("%d\n", ans);} return 0;}


Test results:


Huawei Machine Test-all roads to Rome

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.