We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
packagemainimport("bufio""fmt""io""os""strconv""strings")const(VISITED=1UNVISITED=-1)/* * Complete the 'journeyToMoon' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. INTEGER n * 2. 2D_INTEGER_ARRAY astronaut */funcjourneyToMoon(nint32,astronaut[][]int32)int64{varcomponentsSize[]int32dfsNum:=initDfsNum(n)adjList:=edgeListToAdjList(n,astronaut)foru:=int32(0);u<n;u++{ifdfsNum[u]==UNVISITED{componentSize:=dfs(u,adjList,dfsNum)componentsSize=append(componentsSize,componentSize)}}result:=int64(0)for_,componentSize:=rangecomponentsSize{n-=componentSizeresult+=int64(componentSize)*int64(n)}returnresult}funcdfs(uint32,adjList[][]int32,dfsNum[]int32)int32{dfsNum[u]=VISITEDcomponentSize:=int32(1)for_,v:=rangeadjList[u]{ifdfsNum[v]==UNVISITED{componentSize+=dfs(v,adjList,dfsNum)}}returncomponentSize}funcinitDfsNum(Vint32)[]int32{dfsNum:=make([]int32,V)fori:=int32(0);i<V;i++{dfsNum[i]=UNVISITED}returndfsNum}funcedgeListToAdjList(Vint32,edgeList[][]int32)[][]int32{adjList:=make([][]int32,V)for_,edge:=rangeedgeList{u:=edge[0]v:=edge[1]adjList[u]=append(adjList[u],v)adjList[v]=append(adjList[v],u)}returnadjList}funcmain(){reader:=bufio.NewReaderSize(os.Stdin,16*1024*1024)stdout,err:=os.Create(os.Getenv("OUTPUT_PATH"))checkError(err)deferstdout.Close()writer:=bufio.NewWriterSize(stdout,16*1024*1024)firstMultipleInput:=strings.Split(strings.TrimSpace(readLine(reader))," ")nTemp,err:=strconv.ParseInt(firstMultipleInput[0],10,64)checkError(err)n:=int32(nTemp)pTemp,err:=strconv.ParseInt(firstMultipleInput[1],10,64)checkError(err)p:=int32(pTemp)varastronaut[][]int32fori:=0;i<int(p);i++{astronautRowTemp:=strings.Split(strings.TrimRight(readLine(reader)," \t\r\n")," ")varastronautRow[]int32for_,astronautRowItem:=rangeastronautRowTemp{astronautItemTemp,err:=strconv.ParseInt(astronautRowItem,10,64)checkError(err)astronautItem:=int32(astronautItemTemp)astronautRow=append(astronautRow,astronautItem)}iflen(astronautRow)!=2{panic("Bad input")}astronaut=append(astronaut,astronautRow)}result:=journeyToMoon(n,astronaut)fmt.Fprintf(writer,"%d\n",result)writer.Flush()}funcreadLine(reader*bufio.Reader)string{str,_,err:=reader.ReadLine()iferr==io.EOF{return""}returnstrings.TrimRight(string(str),"\r\n")}funccheckError(errerror){iferr!=nil{panic(err)}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Journey to the Moon
You are viewing a single comment's thread. Return to all comments →
Golang Solution