首頁  >  文章  >  web前端  >  分享一個跟前端相關演算法題

分享一個跟前端相關演算法題

零下一度
零下一度原創
2017-06-24 11:59:181254瀏覽

下面說一個跟前端有點相關並且有點趣的一道演算法題。

題目:

平面上有若干個不特定的形狀,如下圖所示。請寫出程式求出物體的個數,以及每個不同物體的面積。


 

分析

#想知道有多少個圖形,想到的就是先取得圖片中的每個像素點然後判取得像素點的背景顏色(RGBA)。想要獲得圖片中的每個像素點,那就可以聯想到使用h5的canvas。
如下:

菜鳥教學中canvas的getimagedata方法

  • #書寫html標籤。

    <canvas id="canvas" height="200" width="350">对不你,你的浏览器不支持Canvas</canvas>
  • js取得canvas物件

    let ctxt = canvas.getContext(&#39;2d&#39;);
  • #js建立image物件

    let img = new Image;
    img.src = &#39;./image.png&#39;; //图片路径
    img.onload = function(){}  //加载成功后的执行函数,之后的代码就写在其中
  • ##建立儲存圖片像素點的二維數組

    let coordinates = [];for(let i=0; i<200; i++){
         coordinates[i] = [];
    }

  • 取得像素點,也就是使用getimagedata方法。

    ctxt.drawImage(img, 0, 0);  //将图片画如canvas
    let data = ctxt.getImageData(0, 0, 350, 200).data;//读取整张图片的像素。

  • 將像素存入二維陣列

    let x=0,y=0;  //二维数组的行和列, x:列  y:行
    for(let i =0,len = data.length; i<len;i+=4){
          let red = data[i],//红色色深
          green = data[i+1],//绿色色深
          blue = data[i+2],//蓝色色深
          alpha = data[i+3];//透明度      //把每个像素点,以二位数组的形式展开
          if(`${red} ${green} ${blue}` === &#39;210 227 199&#39;){
              coordinates[y][x] = 0;
          }else{
              coordinates[y][x] = 1;
          }
          x++;
          if(x >= 350){
              x = 0;
              y++;
          }
    }

  • #目前程式碼如下:

    (function(){
          let ctxt = canvas.getContext(&#39;2d&#39;);
          let img = new Image;
          let coordinates = [];
          let h = 200,
              w = 350;
          for(let i=0; i<200; i++){
              coordinates[i] = [];
          }
          img.src = './image.png'; //图片路径
          img.onload = function(){
              ctxt.drawImage(img, 0, 0);
              let data = ctxt.getImageData(0, 0, 350, 200).data;//读取整张图片的像素。
              let x=0,y=0;
              for(let i =0,len = data.length; i= 350){
                          x = 0;
                          y++;
                      }
                  }
                  console.log(coordinates);
          }
      })();

  • 如圖:


image.png
  • 構成類似如下二維陣列:

    0,0,0,0,0,0,0,0,0,0,0,0

    0,0,1,1,1,0,0,0,0,0 ,0,0
    0,1,1,1,1,0,0,0,0,0,0,0
    0,1,1,1,0,0,0,1,1 ,1,1,0
    0,0,0,0,0,0,1,1,1,0,0,0
    0,0,0,0,0,0,1,1 ,1,0,0,0
    0,0,0,0,0,0,0,0,0,0,0,0

那麼我們就只需要知道二維數組中這種連續為1的塊有多少個就知道了圖片中形狀有多少個,並且塊中有多少個1,那麼這個塊的面積就是1的個數。

遞迴回溯演算法

//计算连续的面积和个数
const linkSum = (i,j,num)=>{//走过的路就置0
      coordinates[i][j] = 0;
      num++;      //向上
      if((i+1 < h) && coordinates[i+1][j] == 1){
        num = linkSum(i+1 , j , num);
      }      //向下
      if((j+1 < w) && coordinates[i][j+1] == 1){
        num = linkSum(i , j+1 , num);
      }      //向左
      if((i-1 >= 0) && coordinates[i-1][j] == 1){
        num = linkSum(i-1 , j , num);
      }      //向右
    if((j-1 >= 0) && coordinates[i][j-1] == 1){
        num = linkSum(i , j-1 , num);
    }

    return num;
}

不熟悉的,直接百度就好,這裡就不多說了,其實程式碼就反應了很多資訊。

使用演算法,統計併計算出結果。

const getCountAndArea = () =>{let sum = [];let count = 0;for(let i = 0; i < h; i++)  //遍历二维数组
    {      for(let j = 0; j < w; j++)
      {       //连续1的个数       if(coordinates[i][j] == 1)
       {let buf = 0;  //连续1的个数
        buf = linkSum(i,j,buf);count++;  //形状的总数
        sum.push({
            index: count,   //第几个形状
            area: buf         //形状的面积
        });
       }
      }
    }return {count,
        sum
    };
}

最後的程式碼

(function(){
        let ctxt = canvas.getContext(&#39;2d&#39;);
        let img = new Image;
        let coordinates = [];
        let h = 200,
            w = 350;
        for(let i=0; i<200; i++){
            coordinates[i] = [];
        }
        img.src = './image.png'; //图片路径
        img.onload = function(){
            ctxt.drawImage(img, 0, 0);
            let data = ctxt.getImageData(0, 0, 350, 200).data;//读取整张图片的像素。
            let x=0,y=0;
            for(let i =0,len = data.length; i= 350){
                        x = 0;
                        y++;
                    }
                }
                // console.log(coordinates);
                let rst = getCountAndArea();
                // console.log(rst);
                console.log('个数: ' + rst.count);
                for(let i=0; i{
            let sum = [];
            let count = 0;
            for(let i = 0; i < h; i++)
            {
              for(let j = 0; j < w; j++)
              {
               //连续1的个数
               if(coordinates[i][j] == 1)
               {
                let buf = 0;
                buf = linkSum(i,j,buf);
                count++;
                sum.push({
                    index: count,
                    area: buf
                });
               }
              }
            }
            return {
                count,
                sum
            };
        }

        //计算连续的面积和个数
        const linkSum = (i,j,num)=>{
            //走过的路就置0
          coordinates[i][j] = 0;
          num++;
          //向上
          if((i+1 < h) && coordinates[i+1][j] == 1){
            num = linkSum(i+1 , j , num);
          }
          //向下
          if((j+1 < w) && coordinates[i][j+1] == 1){
            num = linkSum(i , j+1 , num);
          }
          //向左
          if((i-1 >= 0) && coordinates[i-1][j] == 1){
            num = linkSum(i-1 , j , num);
          }
          //向右
        if((j-1 >= 0) && coordinates[i][j-1] == 1){
            num = linkSum(i , j-1 , num);
        }

        return num;
        }
    })();

運行的結果:

學習過程中遇到什麼問題或想取得學習資源的話,歡迎加入學習交流群

343599877,我們一起學習前端!

以上是分享一個跟前端相關演算法題的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn