演算法導論22.1-6

來源:互聯網
上載者:User

  找到一個矩陣標記法的有向無權圖中的"匯",定義為,入度為|V| - 1,出度為0的頂點.這樣的頂點,一個圖中只能有一個.或者沒有.這個問題,是以前沒有接觸過的,覺得很有用,所以去寫了下.

  起初寫的東西,很糟糕.我給帶出來了,起初的想法,孩子一樣純真.確實效率不高.而且浪費空間.答案給的實現,更多地利用了矩陣的特點.而且從問題的定義出發,邏輯也不難.很不錯.

  而且,自覺地注釋自己寫得也不錯,都是最近<<代碼大全2>>帶給我的.非常感激大藍哥..

  不多說了,直接貼吧.非常帥的代碼.

  判斷某頂點是不是匯.

//Ignore to judge range of  vertexIndex.bool GraphRepresentAsAdjacentMatrix ::isSink (const int vertexIndex){if (m_currentSize < m_size){std ::cerr << m_size - m_currentSize << "Vertex(es) has(have) not been input yet, can't execute this operation." << std ::endl ;return NoUniversalSinkVertex ;}//Test V[pointIndex] as a start vertex.for (int i = 0; i < m_size; ++i){//If it has an outgoing edge.if (m_matrix[vertexIndex][i] != NotAdjoinTo){return false ;}}//Test V[pointIndex] as an end vertex.for (int i = 0; i < vertexIndex; ++i){if (NotAdjoinTo == m_matrix[i][vertexIndex]){return false ;}}for (int i = vertexIndex + 1; i < m_size; ++i){if (NotAdjoinTo == m_matrix[i][vertexIndex]){return false ; }}//Otherwisw V[pointIndex] is a universal sink vertex, return true.return true ;}

  接下來,找出匯的下標,如果有.並返回.否則返回-1.

int GraphRepresentAsAdjacentMatrix ::indexOfuniversalSink (void){if (m_currentSize < m_size){std ::cerr << m_size - m_currentSize << "Vertex(es) has(have) not been input yet, can't execute this operation." << std ::endl ;return NoUniversalSinkVertex ;}int i = 0 ;int j = 0 ;while (i < m_size && j < m_size){//If V[i] has an outgoing edge.if (m_matrix[i][j] != NotAdjoinTo){//Test next vertex as a start vertex.++i ;}else{//Test next vertex as an end vertex.++j ;}}//If there isn't a vertex has none outgoing edge.if (m_size == i){return NoUniversalSinkVertex ;}//Testing if all vertexes except V[i] has an outgoing edge to V[i]for (int k = 0; k < i; ++k){//If find a vertex hasn't an outgoing edge to V[i].if (NotAdjoinTo == m_matrix[k][i]){return NoUniversalSinkVertex ;}}for (int k = i + 1; k < m_size; ++k){//If find a vertex hasn't an outgoing edge to V[i].if (NotAdjoinTo == m_matrix[k][i]){return NoUniversalSinkVertex ;}}//Otherwisw, V[i] is the universal sink vertex.//return the index i of it.return i ;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.